我会使用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
是包含不同列中不同前缀结果的矩阵。