使用列名模式对 R 中的多个列进行求和,并更改列数(2 到 3)

问题描述 投票:0回答:1

我有一个包含 10 列的数据框。

我需要

  • 首先将列 1+2 和 3+4 加在一起,

  • 然后总结5+6+7和8+9+10列;

  • 并保存为数据框。

我已经让它工作(见下文),但是手动使用 2

sapply
功能,然后是
t
rbind
,因此我寻求更优雅的解决方案。

列名在它们之间呈现出清晰的模式

前 4 列 的列表如下所示:

“on_b_, off_b_”
并重复(因此我总结了列 1 和 2,然后是 3 和 4

接下来的 6 列 的列表如下所示:

“on_b_, something else in between, off_b_”
并重复(因此我总结了 5 & 6 & 7 然后是 8 & 9 & 10

一旦再次看到列表的开头,我需要重新启动该功能开头一个是名字以

on_b_
:

开头的列

on_b_(两者之间完全不相关的其他内容,例如 CC_,或者什么都没有)off_b_

这是可重现的代码块:

df = structure(list(on_b_pos_1 = 64, off_b_4 = 25, 
                    on_b_6 = 28, off_b_8 = 157, 
                    on_b_3 = 42, CC_2 = 0,  off_b_4 = 125, 
                    on_b_5 = 51, CC_7 = 0, off_b_8 = 15), 
               row.names = 14L, class = "data.frame")

这是我以前做过的并且有效:

# adding together TWO columns
a <- data.frame(sapply(seq(1,4,by=2),function(i) rowSums(df[,i:(i+1)])))

# check whether the function i is getting the correct columns where it restarts
# seq(1,4,by=2) 

# adding together THREE columns
b <- data.frame(sapply(seq(5,ncol(df),by=3),function(i) rowSums(df[,i:(i+2)])))

# transpose
a <- t(a)
b <- t(b)

c <- cbind(a, b)

结果应该是这样的:

Column 1  Column 2  Column 3  Column 4
  89        185       167        66
r dataframe dplyr sapply
1个回答
1
投票

您可以使用

map2
包中的
purrr
函数,您可以在其中查找以
grep
的“on”或“off”开头的列索引。

library(purrr)

map2_int(grep("^on", colnames(df)), 
         grep("^off", colnames(df)), 
         ~rowSums(df[, .x:.y]))

[1]  89 185 167  66
© www.soinside.com 2019 - 2024. All rights reserved.