Loop through data.table and create new columns basis some condition

后端 未结 3 1940
无人共我
无人共我 2021-01-13 04:34

I have a data.table with quite a few columns. I need to loop through them and create new columns using some condition. Currently I am writing separate line of condition for

3条回答
  •  离开以前
    2021-01-13 05:18

    For completeness, it should be noted that dplyr's mutate_each provides a handy way of tackling such problems:

    library(dplyr)
    
    result <- DT %>%
        group_by(town,tc) %>%
        mutate_each(funs(mean,sd,
                         uplimit = (mean(.) + 1.96*sd(.)),
                         lowlimit = (mean(.) - 1.96*sd(.)),
                         Aoutlier = as.integer(. >= mean(.) - 1.96*sd(.) &
                                                   . <= mean(.) - 1.96*sd(.))),
                    -town,-tc)
    

提交回复
热议问题