快速求和 R 数据框中的多列 [英] summing multiple columns in an R data-frame quickly
本文介绍了快速求和 R 数据框中的多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像 mtcars
这样的数据框,还有一个列名的字符串向量,比如 c("mpg", "cyl", "disp", "hp", "drat")
,我想把所有的列加在一起组成一个新的列.
I have a data frame like mtcars
, and a string vector of column names such as c("mpg", "cyl", "disp", "hp", "drat")
, and I would like to sum together all of the columns into a new one.
我通常会使用类似
mtcars %>% transmute(new_col = mpg + cyl + disp + hp + drat)
new_col
1 300.90
2 300.90
3 231.65
4 398.48
5 564.85
6 356.86
7 630.51
但是,当您将 100 个列名存储在一个向量中时,这会变得非常乏味.
However, this becomes very tedious when you have 100s of column names, stored in a vector.
所以我的问题是,有没有办法将许多列相加,其中列名保存在一个字符串向量中?
So my question is, is there a way of summing together lots of columns, where the column names are held in a vector of strings?
推荐答案
使用 rowSums
函数.
colnms=c("mpg", "cyl", "disp", "hp", "drat")
mtcars$new_col<-rowSums(mtcars[,colnms])
这篇关于快速求和 R 数据框中的多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文