如何在dplyr中执行向量/行总和(逐元素)? [英] How to do vector/row sum (element by element) in dplyr?

查看:88
本文介绍了如何在dplyr中执行向量/行总和(逐元素)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 dplyr 中进行向量求和(即行和,逐个元素)。

How to do vector sum (i.e. row sum, element by element) in dplyr.

要使用的数据:

> dt <- ggplot2::diamonds[1:3,5:10]  
   depth table price     x     y     z
1:  61.5    55   326  3.95  3.98  2.43
2:  59.8    61   326  3.89  3.84  2.31
3:  56.9    65   327  4.05  4.07  2.31

我想添加一列 Total dt ,这将等于列的元素与元素之和 cols<-3:5

I'd like to add a column Total to the dt which will be equal to element by element sum of columns" cols <- 3:5

NB1:我知道如何在data.table中执行此操作: dt [,Total:= rowSums(.SD),.SDcols = cols]

NB1: I know how to do it in data.table: dt [ , Total:= rowSums(.SD), .SDcols=cols]

NB2:在dplyr中,我们可以这样做: dt%>%mutate(Total = x + y + z)。但是如何以与列名无关的方式 cols = 3:5 (或对于 cols = 3:5000 )?

NB2: In dplyr, we can do: dt %>% mutate(Total=x+y+z). But how to do it in column-name agnostic waycols=3:5 (or for cols=3:5000 ) ?

PS。最初在此处提出此问题:如何在data.table和dplyr中执行向量/行总和(逐元素)?,但是在被回答之前,有人将其关闭为Duplicate。

PS. This question was originally asked here: How to do vector/row sum (element by element) in data.table and dplyr?, but was closed by someone as Duplicate before it was answered.

推荐答案

dplyr 选项将使用 c_across() rowSums() mutate()

选项1:

library(dplyr)
#Data
dt <- ggplot2::diamonds[1:3,5:10] 

#Option 1
dt %>% rowwise() %>%
  mutate(sumVar = sum(c_across(price:y)))

输出:

# A tibble: 3 x 7
# Rowwise: 
  depth table price     x     y     z sumVar
  <dbl> <dbl> <int> <dbl> <dbl> <dbl>  <dbl>
1  61.5    55   326  3.95  3.98  2.43   334.
2  59.8    61   326  3.89  3.84  2.31   334.
3  56.9    65   327  4.05  4.07  2.31   335.

选项2:

#Option 2
dt %>% mutate(sumVar = rowSums(.[3:5]))

输出:

# A tibble: 3 x 7
  depth table price     x     y     z sumVar
  <dbl> <dbl> <int> <dbl> <dbl> <dbl>  <dbl>
1  61.5    55   326  3.95  3.98  2.43   334.
2  59.8    61   326  3.89  3.84  2.31   334.
3  56.9    65   327  4.05  4.07  2.31   335.

这篇关于如何在dplyr中执行向量/行总和(逐元素)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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