我有一个 55000 行的表,看起来像这样(左表):
(生成示例数据的代码如下)
现在我需要将这个表的每一行转换为 6 行,每行包含一个字母“六聚体”(图片右表)并进行一些计算:
# input for the function is one row of source table, output is 6 rows
splithexamer <- function(x){
dir <- x$dir # strand direction: +1 or -1
pos <- x$pos # hexamer position
out <- x[0,] # template of output
hexamer <- as.character(x$hexamer)
for (i in 1:nchar(hexamer)) {
letter <- substr(hexamer, i, i)
if (dir==1) {newpos <- pos+i-1;}
else {newpos <- pos+6-i;}
y <- x
y$pos <- newpos
y$letter <- letter
out <- rbind(out,y)
}
return(out);
}
# Sample data generation:
set.seed(123)
size <- 55000
letters <- c("G","A","T","C")
df<-data.frame(
HSid=paste0("Hs.", 1:size),
hexamer=replicate(n=size, paste0(sample(letters,6,replace=T), collapse="")),
chr=sample(c(1:23,"X","Y"),size,replace=T),
pos=sample(1:99999,size,replace=T),
dir=sample(c(1,-1),size,replace=T)
)
现在我想得到一些建议,什么是将我的函数应用到每一行的最有效方法。到目前为止,我尝试了以下操作:
# Variant 1: for() with rbind
tmp <- data.frame()
for (i in 1:nrow(df)){
tmp<-rbind(tmp,splithexamer(df[i,]));
}
# Variant 2: for() with direct writing to file
for (i in 1:nrow(df)){
write.table(splithexamer(df[i,]),file="d:/test.txt",append=TRUE,quote=FALSE,col.names=FALSE)
}
# Variant 3: ddply
tmp<-ddply(df, .(HSid), .fun=splithexamer)
# Variant 4: apply - I don't know correct syntax
tmp<-apply(X=df, 1, FUN=splithexamer) # this causes an error
以上所有都非常慢,我想知道是否有更好的方法来解决这个任务...
最佳答案
使用 data.table
的解决方案:
df$hexamer <- as.character(df$hexamer)
dt <- data.table(df)
dt[, id := seq_len(nrow(df))]
setkey(dt, "id")
dt.out <- dt[, { mod.pos <- pos:(pos+5); if(dir == -1) mod.pos <- rev(mod.pos);
list(split = unlist(strsplit(hexamer, "")),
mod.pos = mod.pos)}, by=id][dt][, id := NULL]
dt.out
# split mod.pos HSid hexamer chr pos dir
# 1: G 95982 Hs.1 GCTCCA 5 95982 1
# 2: C 95983 Hs.1 GCTCCA 5 95982 1
# 3: T 95984 Hs.1 GCTCCA 5 95982 1
# 4: C 95985 Hs.1 GCTCCA 5 95982 1
# 5: C 95986 Hs.1 GCTCCA 5 95982 1
# ---
# 329996: A 59437 Hs.55000 AATCTG 7 59436 1
# 329997: T 59438 Hs.55000 AATCTG 7 59436 1
# 329998: C 59439 Hs.55000 AATCTG 7 59436 1
# 329999: T 59440 Hs.55000 AATCTG 7 59436 1
# 330000: G 59441 Hs.55000 AATCTG 7 59436 1
主线解释:
by=id
将按id
分组,因为它们都是唯一的,所以它将按每一行分组,一次一个。- 然后,
{}
中的那些将mod.pos
设置为pos:(pos+6-1)
并且如果dir == -1
反转它。 - 现在,
list
参数:它通过使用strsplit
从六聚体中创建 6 个核苷酸来创建列split
并设置mod.pos
我们已经在之前的步骤中计算过了。 - 这将生成一个包含列
id、split 和 mod.pos
的data.table
。 - 下一部分
[dt]
是data.table 的 X[Y]
语法的典型用法,它根据 关键列(=id
,此处)。由于每个id
有 6 行,因此在此连接期间,您会复制dt
中的所有其他列。
我建议您先查看data.table
FAQ,然后查看其文档(介绍)。这些链接可以通过安装包并加载它然后键入 ?data.table
来获得。我还建议您通过测试 data.table 一个一个地完成其中的许多示例,以实际了解 data.table 的功能。
希望这对您有所帮助。
关于r - 大表处理(需要建议),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15504069/