如何使用列索引与dplyr对所选列进行横向求和? [英] How to do rowwise summation over selected columns using column index with dplyr?

查看:252
本文介绍了如何使用列索引与dplyr对所选列进行横向求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In dplyr, how do you perform rowwise summation over selected columns (using column index)?

这不起作用

> 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

我可以执行以下操作,但不美观

I can do the following, but it's not beautiful

> 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
..     ...  ...          ...         ...          ...         ...

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

Is there more syntactically nicer way to achieve this?

编辑:与其他问题不同,因为我想对使用列索引

It's different from other questions, because I want to do rowwise operation on the columns selected by using column indices"

推荐答案

如上所述,您可以通过以下方式完成任务:

As already said in the comment, you can accomplish your task with:

iris %>% mutate(sum=Reduce("+",.[1:4]))

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

In this case also the base rowSums works:

iris$sum<-rowSums(iris[,1:4])

这篇关于如何使用列索引与dplyr对所选列进行横向求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆