Hi all,
I have a df that looks basically like this:
Id A B C total
3 5 0 1 6
4 5 4 3 12
5 3 2 4 9
I want to divide each cell in variables A-C with the total and add the quotient in new columns, like this:
Id A B C total prop_a prop_b prop_c
3 5 0 1 6
4 5 4 3 12
5 3 2 4 9
I wrote the following code:
for (i in 5:7){
j = 2 #starting counter
df$i_prop <- cbind(df$"[j]"/df$total)
j = j + 1
}
And got this message:
Error in `$<-.data.frame`(`*tmp*`, "i_prop", value = numeric(0)) :
replacement has 0 rows, data has 126
Can you guys help? I don't understand the error and how to fix it (sorry, still newbie)
Thanks,
Simon
--
You received this message because you are subscribed to the Google Groups "Israel R User Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to israel-r-user-g...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Thanks Amit.
The dplyr solution works, but I have 51 columns to compute – Is there a way to write this command without repeating the division 51 times?
BTY – The generic solution doesn't work, still trying to see why.
Simon
The generic way should work for you. Maybe you shoulf convert to a matrix first. Will check later
use the linked pdf as a guide for the select or contains and in general for dplyr and tidyr
https://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf
The generic works – had a small typo…
thanks for all the advice!
Simon