如何使用列索引与dplyr对选定列进行行向求和?

Alb*_*lby 5 r dplyr

dplyr,如何对所选列执行行向求和(使用列索引)?

这不起作用

> iris  %>% mutate(sum=sum(.[1:4])) %>% head
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species    sum
1          5.1         3.5          1.4         0.2  setosa 2078.7
2          4.9         3.0          1.4         0.2  setosa 2078.7
3          4.7         3.2          1.3         0.2  setosa 2078.7
4          4.6         3.1          1.5         0.2  setosa 2078.7
5          5.0         3.6          1.4         0.2  setosa 2078.7
6          5.4         3.9          1.7         0.4  setosa 2078.7
Run Code Online (Sandbox Code Playgroud)

我可以做到以下几点,但它并不美丽

> iris %>% mutate(index=1:n()) %>%  
                gather("param", "value", 1:4)  %>% 
                group_by(index) %>% 
                mutate(sum=sum(value)) %>% 
                spread(param, value) %>% select(-index)
Source: local data frame [150 x 6]

   Species  sum Sepal.Length Sepal.Width Petal.Length Petal.Width
1   setosa 10.2          5.1         3.5          1.4         0.2
2   setosa  9.5          4.9         3.0          1.4         0.2
3   setosa  9.4          4.7         3.2          1.3         0.2
4   setosa  9.4          4.6         3.1          1.5         0.2
5   setosa 10.2          5.0         3.6          1.4         0.2
6   setosa 11.4          5.4         3.9          1.7         0.4
7   setosa  9.7          4.6         3.4          1.4         0.3
8   setosa 10.1          5.0         3.4          1.5         0.2
9   setosa  8.9          4.4         2.9          1.4         0.2
10  setosa  9.6          4.9         3.1          1.5         0.1
..     ...  ...          ...         ...          ...         ...
Run Code Online (Sandbox Code Playgroud)

是否有更多的语法更好的方法来实现这一目标?

编辑:它与其他问题不同,因为我想对使用列索引选择的列进行逐行操作"

nic*_*ola 10

正如评论中已经说过的那样,您可以通过以下方式完成任务:

iris %>% mutate(sum=Reduce("+",.[1:4]))
Run Code Online (Sandbox Code Playgroud)

在这种情况下,基础rowSums工作:

iris$sum<-rowSums(iris[,1:4])
Run Code Online (Sandbox Code Playgroud)

  • 我意识到 OP 想要使用列索引,但是有没有办法使用列名?我正在考虑类似 select 函数 select(df, V4:V13) 的东西。不知道如何把它放在这里。 (2认同)