具有特定名称的列的行式总和 [英] Row-wise sum for columns with certain names

查看:22
本文介绍了具有特定名称的列的行式总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个样本数据:

SampleID  a      b     d     f       ca      k     l    cb
1         0.1    2     1     2       7       1     4    3
2         0.2    3     2     3       4       2     5    5
3         0.5    4     3     6       1       3     9    2

我需要找到名称上有共同点的列的行列总和,例如行式 sum(a, ca) 或行式 sum(b,cb).问题是我有很大的 data.frame,理想情况下我可以写列标题中的常见内容,这样代码就会只选择那些列进行求和

I need to find row-wise sum of columns which have something common in names, e.g. row-wise sum(a, ca) or row-wise sum(b,cb). The problem is that i have large data.frame and ideally i would be able to write what is common in column header, so that code would pick only those columns to sum

在此先感谢您的帮助.

推荐答案

我们可以用 grep 选择有 'a' 的列,对列进行子集化并执行 rowSums'b' 列也一样.

We can select the columns that have 'a' with grep, subset the columns and do rowSums and the same with 'b' columns.

 rowSums(df1[grep('a', names(df1)[-1])+1])
 rowSums(df1[grep('b', names(df1)[-1])+1])

这篇关于具有特定名称的列的行式总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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