且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

dplyr,R:一次计算多个列中的特定值

更新时间:2022-01-12 23:09:21

如果您在乎以计数开头的名称。您可以在dplyr管道中这样做:

If you care about the names starting with "counts." you could do it like this in a dplyr pipe:

md %>% 
  group_by(device) %>% 
  summarise_each_(funs(sum(.==5,na.rm=TRUE)), myvars) %>% 
  setNames(c(names(.)[1], paste0("counts.", myvars)))
#Source: local data frame [3 x 4]
#
#  device counts.a counts.b counts.c
#1      1        1        2        0
#2      2        0        1        0
#3      3        1        0        2

还有另一个关于如何命名dplyr的 mutate_each 产生的新列的问答(其行为与 summarise_each )在这里:dplyr中的 mutate_each:如何选择某些列并为突变列赋予新名称?

There's another Q&A about how one can name new columns produced by dplyr's mutate_each (which behaves the same way as summarise_each) here: mutate_each in dplyr: how do I select certain columns and give new names to mutated columns?.