简体   繁体   English

部分字符串匹配的列总和,其名称从列表中导入。 [R

[英]Sum of columns with partial string match, with names imported from a list. R

I'm working with data tables like so: 我正在使用这样的数据表:

ID <- c("ChrM","ChrM","ChrM","ChrM","ChrM")
pos <- c(5,6,7,10,11)
cr.H.MN.8A <- c(0,0,3,0,1)
cr.H.MN.8B <- c(2,1,0,1,0)
cr.H.MR.8A<-c(0,0,0,0,1)
cr.H.MR.8B<-c(0,2,0,0,1)
cr.H.MR2.8A<-c(0,1,1,0,0)
cr.H.MR2.8B<-c(0,1,0,0,0)
dfa <- data.table(ID,pos,cr.H.MN.8A,cr.H.MN.8B,cr.H.MR.8A,cr.H.MR.8B,cr.H.MR2.8A,cr.H.MR2.8B)



dfa
         ID pos cr.H.MN.8A cr.H.MN.8B cr.H.MR.8A cr.H.MR.8B cr.H.MR2.8A cr.H.MR2.8B
    1: ChrM   5          0          2          0          0           0           0
    2: ChrM   6          0          1          0          2           1           1
    3: ChrM   7          3          0          0          0           1           0
    4: ChrM  10          0          1          0          0           0           0
    5: ChrM  11          1          0          1          1           0           0
    > 

Now, on an earlier question I asked how I could use the similiraties on the name strings to add them up 现在,在一个较早的问题上,我问我如何使用名称字符串上的相似性将它们加起来

dfa[,`H.MN.8` := as.numeric(rowSums(.SD) > 1), .SDcols = grep("cr.H.MN.8", names(dfa))]

Which worlks flawlessly. 完美无瑕的蠕动。 But I got another question; 但是我还有另一个问题。 is it possible to auto assign the parameters needed to separate the string? 是否可以自动分配分隔字符串所需的参数? I've got the names of each column on a list (they used to be different data.frames), so could I use it to replace the HM.MN.8 and thus make it more easily computed? 我在列表上有每一列的名称(它们以前是不同的data.frames),所以我可以用它代替HM.MN.8 ,从而使计算更容易吗? Thanks! 谢谢!

The names are so: 名称如下:

names(dfb)<-c("cr.H.MN.8A","cr.H.MN.8B","cr.H.MR.8A","cr.H.MR.8B","cr.H.MR2.8A","cr.H.MR2.8B")

you can try using 你可以尝试使用

varName <- c("H.MR2","H.MN.8")
eval(parse(text=paste0("dfa[,`",varName,"` := as.numeric(rowSums(.SD) > 1), .SDcols = grep('",varName,"', names(dfa))]")))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM