行在其名称中具有特定模式的列上求和 [英] Row sums over columns with a certain pattern in their name
本文介绍了行在其名称中具有特定模式的列上求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个data.table这样
I have a data.table like this
dput(DT)
structure(list(ref = c(3L, 3L, 3L, 3L), nb = 12:15, i1 = c(3.1e-05,
0.044495, 0.82244, 0.322291), i2 = c(0.000183, 0.155732, 0.873416,
0.648545), i3 = c(0.000824, 0.533939, 0.838542, 0.990648), i4 = c(0.044495,
0.82244, 0.322291, 0.393595)), .Names = c("ref", "nb", "i1",
"i2", "i3", "i4"), row.names = c(NA, -4L), class = c("data.table",
"data.frame"), .internal.selfref = <pointer: 0x0000000000320788>)
DT
# ref nb i1 i2 i3 i4
# 1: 3 12 0.000031 0.000183 0.000824 0.044495
# 2: 3 13 0.044495 0.155732 0.533939 0.822440
# 3: 3 14 0.822440 0.873416 0.838542 0.322291
# 4: 3 15 0.322291 0.648545 0.990648 0.393595
现在我想计算行数,但只包括以i(i1,i2等)开头的列
Now I want to calculate rows sums, but only including columns which start with an "i" ("i1", "i2", etc)
我使用 grep
来创建要求和的列名称的向量:
I have used grep
to create a vector of the column names to be summed:
listCol <- colnames(DT)[grep("i", colnames(DT))]
listCol
# [1] "i1" "i2" "i3" "i4"
然后我尝试循环列:
DT$sum <- rep.int(0, nrow(DT))
for (i in listCol){
DT$sum = DT$sum + DT[ , get(i)]
}
...给出所需的输出:
...which gives the desired output:
DT
# ref nb i1 i2 i3 i4 sum
# 1: 3 12 0.000031 0.000183 0.000824 0.044495 0.045533
# 2: 3 13 0.044495 0.155732 0.533939 0.822440 1.556606
# 3: 3 14 0.822440 0.873416 0.838542 0.322291 2.856689
# 4: 3 15 0.322291 0.648545 0.990648 0.393595 2.355079
如何改善我的代码?非常感谢!
How can I improve my code? Many thanks!
这个子问题部分包含了上一个问题的答案:
This sub question include partially the answer to the previous one :
如何避免这种奇怪的符号:
How to avoid this kind of strange notation :
myrowMeans = function (x){
rowMeans(x, na.rm = TRUE)
}
DT[ , var := myrowMeans(.SD-myrowMeans(.SD)^2), .SDcols = grep("i", colnames(DT))]
推荐答案
c $ c>减少
You may also try with Reduce
DT[, Sum := Reduce(`+`, .SD), .SDcols=listCol][]
# ref nb i1 i2 i3 i4 Sum
#1: 3 12 0.000031 0.000183 0.000824 0.044495 0.045533
#2: 3 13 0.044495 0.155732 0.533939 0.822440 1.556606
#3: 3 14 0.822440 0.873416 0.838542 0.322291 2.856689
#4: 3 15 0.322291 0.648545 0.990648 0.393595 2.355079
注意:如果有NA值,在之前应该用'0'替换 ie
NOTE: If there are "NA" values, it should be replaced with '0' before Reduce
i.e.
DT[, Sum := Reduce(`+`, lapply(.SD, function(x) replace(x,
which(is.na(x)), 0))), .SDcols=listCol][]
这篇关于行在其名称中具有特定模式的列上求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文