Newbie struggling in rowwise percent calculation of two columns

Hi everyone, I´m brand new to RStudio and I have some difficulties in a quite simple (I suppose) task. For a large dataset (see a short abstract) of "ID" and respective numeric values of a total budget and personnel costs, I want to calculate the share of personnel costs of the total budget per ID in percent.

Of course, I´m able to calculate it manually, but due to the size of the dataset, is it possible to achieve these results by a formula?

grafik

Thank you a thousand time for your help in advance!

1 Like

Simple example

dat1 <- data.frame(
  stringsAsFactors = FALSE,
                id = c("A", "B", "C"),
            budget = c(1066500L, 100464L, 77618L),
    personal_costs = c(658168L, 254310L, 67826L)
        )

dat1$percent <-  dat1$personal_costs / sum(dat1$budget) * 100

There are other ways to do this.

For a general outline for asking questions

A handy way to supply some sample data is the dput() function. In the case of a large dataset something like dput(head(mydata, 100)) should supply the data we need. Just do dput(mydata) where mydata is your data. Copy the output and paste it here.

1 Like

Are you asking to calculate (personnel_costs / budget)*100?

Then:

library(tidyverse)
a_large_dataset %>%
    dplyr::mutate(
    share_of_personnel_costs = (personnel_costs / budget)*100
    )
1 Like

Thank you so much for your immediate answer, it worked perfectly!

Thank you also very much for your immediate answer, it likewise worked perfectly!

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.