Home > Blockchain >  sapply mult column and dataframe
sapply mult column and dataframe

Time:01-24

I am new to R using SPSS for many years.

my data column are.

"ffqnum"   "tot_wt"   "ffq_name" "foodcode" "foodname" "nut203"   "nut204"   "nut205"   "nut208"
  num       double    char        num        char      double      double     double     double   

I use sapply to calculate new values for 4 column

ffq2 <- sapply(ffq116[, c(6:num_col)] ,function(i) i * ffq116$tot_wt)
ffq2 = data.frame(ffq2)

the new dataframe have only 4 columns

"nut203" "nut204" "nut205" "nut208"

I am looking for advise how to salve the flowing task: Is there a way using sapply or other method to get columns "ffqnum" "tot_wt" "ffq_name" "foodcode" "foodname" back into the calculate dataframe. Is there a way to add a key column to the new dataframe. I know I can use loop but can it be done using sapply.

CodePudding user response:

You need to reassign back into the corresponding columns.

ffq116[c(6:num_col)] <- sapply(ffq116[c(6:num_col)], function(i) i * ffq116$tot_wt)

I recognize this overwrites your version of ffq116, you may prefer to first copy it with ffq2 <- ffq116 and then operate on that frame instead.

CodePudding user response:

You can use the tidyverse verbs and try the following codes:

library("tidyverse")
ffq2 <- ffq116 %>% mutate_at(.vars = vars(starts_with("nut")), .funs = ~ . * tot_wt)
  •  Tags:  
  • Related