4

示例:我有一个数据框

> a = data.frame(T_a_1=c(1,2,3,4,5),T_a_2=c(2,3,4,5,6),T_b_1=c(3,4,5,6,7),T_c_1=c(4,5,6,7,8),length=c(1,2,3,4,5))
> a    
T_a_1 T_a_2 T_b_1 T_c_1 length
1     2     3     4      1
2     3     4     5      2
3     4     5     6      3
4     5     6     7      4
5     6     7     8      5

我想根据名称在列上添加(或执行一些其他操作,例如 (column1+column2)/length。像 T_a(T_a_1 和 T_a_2)是两列(第 1 和第 2)之间的通用名称,所以我想添加它们。

4

2 回答 2

3

我会使用grep命令来将列名与某种模式相匹配。这里有些例子:

> a = data.frame(T_a_1=c(1,2,3,4,5),
+                T_a_2=c(2,3,4,5,6),
+                T_b_1=c(3,4,5,6,7),
+                T_c_1=c(4,5,6,7,8),
+                length=c(1,2,3,4,5))
> 
> # display only columns that match T_a
> a[,grep('T_a', colnames(a))]
  T_a_1 T_a_2
1     1     2
2     2     3
3     3     4
4     4     5
5     5     6
> 
> # sum
> sum(a[,grep('T_a', colnames(a))])
[1] 35
> 
> #rowsum
> rowSums(a[,grep('T_a', colnames(a))])
[1]  3  5  7  9 11
> 
> # your example (row1 + row2) / length
> rowSums(a[,grep('T_a', colnames(a))]) / a$length
[1] 3.000000 2.500000 2.333333 2.250000 2.200000

更新:

从下面的评论中,我了解到您想要对按公共前缀分组的匹配行求和并除以长度列。以下代码是该问题的一个不优雅的解决方案:

> a = data.frame(ES51_223_1=c(1,2,3,4,5),
+                ES51_312_1=c(2,3,4,5,6),
+                ES52_223_2=c(3,4,5,6,7),
+                ES52_312_2=c(4,5,6,7,8),
+                ES53_223_3=c(1,2,3,4,5),
+                length=c(1,2,3,4,5))
> 
> # get the unique prefixes
> prefixes = unique(unlist(lapply(colnames(subset(a, select=-length)), function(x) { strsplit(x, '_')[[1]][[1]]})))
> 
> f = function(prefix) {
+   return (rowSums(subset(a, select=grep(prefix, colnames(a)))) / a$length)
+ }
> m = matrix(unlist(lapply(prefixes, f)), nrow=nrow(a))
> colnames(m) = prefixes
> m
         ES51     ES52 ES53
[1,] 3.000000 7.000000    1
[2,] 2.500000 4.500000    1
[3,] 2.333333 3.666667    1
[4,] 2.250000 3.250000    1
[5,] 2.200000 3.000000    1

m是包含不同列中不同前缀结果的矩阵。

于 2013-02-18T20:23:02.190 回答
2

这个怎么样?

# data
df <- structure(list(ES51_223_1 = 1:5, ES51_312_1 = 2:6, ES52_223_2 = 3:7, 
      ES52_312_2 = 4:8, ES53_223_3 = 1:5, length = 1:5), 
      .Names = c("ES51_223_1", "ES51_312_1", "ES52_223_2", "ES52_312_2", 
      "ES53_223_3", "length"), row.names = c(NA, -5L), class = "data.frame")

# create indices from factor levels (shortcut)
ids <- gsub("_.*$", "", setdiff(names(df), "length"))
ids <- factor(as.numeric(factor(ids)))
> ids
# [1] 1 1 2 2 3
# Levels: 1 2 3

# use the levels to fetch columns and sum them
o <- sapply(as.numeric(levels(ids)), function(x) {
    rowSums(df[which(ids == x)])/df$length
})

> o
#          [,1]     [,2] [,3]
# [1,] 3.000000 7.000000    1
# [2,] 2.500000 4.500000    1
# [3,] 2.333333 3.666667    1
# [4,] 2.250000 3.250000    1
# [5,] 2.200000 3.000000    1
于 2013-02-18T21:17:20.563 回答