快速汇总R数据帧中的多列 [英] summing multiple columns in an R data-frame quickly

查看:44
本文介绍了快速汇总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屋!

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