R data.table中循环的优化
我使用的是这里的data.table解决方案: 我为循环添加了这个R data.table中循环的优化,r,for-loop,data.table,R,For Loop,Data.table,我使用的是这里的data.table解决方案: 我为循环添加了这个,以便让newCol保存单个单元格中的折叠变量(从第一个dt.out)。然而,运行这个循环需要很多时间。有没有更快的方法 for(i in 1:NROW(dt.out)){ con <- textConnection(dt.out[i,grep("newCol", colnames(dt.out))]) data <- read.csv(con, sep=",", header=FALSE) close(
,以便让newCol
保存单个单元格中的折叠变量(从第一个dt.out
)。然而,运行这个循环需要很多时间。有没有更快的方法
for(i in 1:NROW(dt.out)){
con <- textConnection(dt.out[i,grep("newCol", colnames(dt.out))])
data <- read.csv(con, sep=",", header=FALSE)
close(con)
dt.out[i,grep("newCol", colnames(dt.out))]<- as.numeric(rowMeans(data))
}
for(输入1:NROW(输出)){
与另一个问题中的数据相比,connewCol
似乎是一个额外的列。我猜在获得第一个dt.out
后,您希望取newCol
的折叠值的平均值
您可以通过将newCol
直接替换为sapply(strsplit(.))
来完成此操作。基本上,在获得第一个dt.out
后,请执行以下操作:
dt.out[ , newCol := sapply(strsplit(newCol, ","), function(x) mean(as.numeric(x)))]
代码优化问题应该在CodeReview上提出,而不是StackOverflow
for(i in 1:NROW(dt.out)){
con <- textConnection(dt.out[i,grep("newCol", colnames(dt.out))])
data <- read.csv(con, sep=",", header=FALSE)
close(con)
dt.out[i,grep("newCol", colnames(dt.out))]<- as.numeric(rowMeans(data))
}
dt.out[ , newCol := sapply(strsplit(newCol, ","), function(x) mean(as.numeric(x)))]