rdplyrdata-wrangling

Divide values in some columns by the value of a column and replace in data table


Using R, I want to divide the values in columns 21 through 150 in my data table by the value in column 5 and replace the value that is in columns 21 through 150 with the new divided value. So for example column 21 would be divided by column 5 and the new value in column 21 is then replaced by the quotient. The same for column 22 gets divided by column 5 and then the column 22 value is updated with the divided value.

First I tried this but it does not replace the values in the columns and then output does not have columns 1-20...

df1000 <- df1000[,21:150] / df1000[,5]

so then I tried dplyr but something is wrong

df1000 %>% mutate_at(seq(21:150),funs(df[,21:150]/df[,5]))

Since my sample is so large with 150 columns instead of providing sample data can we use a built-in dataset like iris and I can adjust the column range?


Solution

  • You were really close with your first attempt. Just needed to store the new data back with the same indeces.

    df1000[,21:150] <- df1000[,21:150] / df1000[,5]