首页 文章

对包含字符串列的data.table执行数值运算

提问于
浏览
0

我有一个大表(几十万行),它有一个ID(作为字符串)列,后面是几个数字列,其中包含来自不同样本的测量值 .

我需要进行数值运算,例如缩放和记录数值数据,基于方差进行过滤,然后绘制等...到目前为止,我所做的方法是将数据的数字部分子集化为新变量和过程因此 .

f_na2zero(dt)
dt.num <- dt[,!c("Seq"),with=F]
dt.scaled <- (dt.num + 1) / colSums(dt.num) # +1 to avoid NaN due to logging
dt.log <- log10(dt.scaled)

newdt <- data.table("Seq" = dt$Seq, dt.log)
dt.filtered <- newdt[nchar(Seq) == 207, ]
dt.A <- dt.filtered[, c("Seq", "Lib", "A5_1", "A5_2", "A5_3"), with=F]
dt.B <- dt.filtered[, c("Seq", "Lib", "B5_1", "B5_2", "B5-3"), with=F]

ind.A.highvar <- which(apply(dt.A, 1, var) > sd(as.matrix(dt.A)))
ind.B.highvar <- which(apply(dt.B, 1, var) > sd(as.matrix(dt.B)))
ind.A.highvar2 <- which(apply(dt.A, 1, var) > 2*sd(as.matrix(dt.A)))
ind.B.highvar2 <- which(apply(dt.B, 1, var) > 2*sd(as.matrix(dt.B)))

A.highvar <- dt.A[ind.A.highvar, !c("Seq"), with=F]
A.highvar2 <- dt.A[ind.A.highvar2, !c("Seq"), with=F]
B.highvar <- dt.B[ind.B.highvar, !c("Seq"), with=F]
B.highvar2 <- dt.B[ind.B.highvar2, !c("Seq"), with=F]

par(mfrow=c(2,2))
# plotLines takes a matrix and plots each column as a line, returns indices where data[1,] < data[4,] is true
seqs.A1 <- plotLines(t(A.highvar),"1 Sigma A",c("Lib", "A5-1", "A5-2", "A5-3"))
seqs.B1 <- plotLines(t(B.highvar),"1 Sigma B",c("Lib", "B5-1", "B5-2", "B5-3"))
seqs.A2 <- plotLines(t(A.highvar2),"2 Sigma A",c("Lib", "A5-1", "A5-2", "A5-3"))
seqs.B2 <- plotLines(t(B.highvar2),"2 Sigma B",c("Lib", "B5-1", "B5-2", "B5-3"))

问题是我需要ID才能使用这些数据,但行号会随着我在此过程中根据不同的标准进行过滤而改变 . 我认为需要有一种更简单的方法来处理数据,而不是经常存储新的表和变量,但我无法理解 data.table 索引方案(在你提到它之前,是的,我已经阅读了introduction to data.table vignette

所以在这方面,具体问题:

  • 是否可以对数据表的某些列进行数值运算(即,在进行日志转换时跳过“Seq”列,或者根据方差进行逻辑索引)而不通过中间变量?

  • 如何根据逻辑函数过滤行并同时在特定列上进行oeprate?当我想使用 .SD.SDcolumns 时,是否需要使用分组运算符 by

Edit 根据Roland 's comment here'一个小脚本,它重新创建了我正在使用的数据类型 .

dt <- data.table("Seq" = stringi::stri_rand_strings(100000,200,"[A-Z]"), matrix(rnorm(n = 700000, mean=-3, sd = 1.5), nrow = 100000, ncol = 7, dimnames = list(NULL,c("A5_1","A5_2","A5_3","B5_1", "B5_2","B5_3","Lib"))))

1 回答

  • 2

    对不起,没有什么可以重现的(这里是 Seq 列?)这里也没有你的例子最小也没有解释你想要实现的目标 .

    但是,也许这说明了我对长格式的意思:

    dt <- melt(dt, id.vars = "Id")
    dt[, ind := .GRP, by = Id]
    
    library(ggplot2)
    stdev <- sd(dt[, value])
    ggplot(dt[, if(var(value) > (2 * stdev)) .SD, by = Id], #filter
           aes(x = ind, y = value, color = variable)) +
      geom_line()
    

相关问题