动态文件名加载和for循环处理

时间:2019-05-16 13:43:00

标签: r for-loop printf

我正在处理一些.xlsx,它们的名称类似time1_drug1,time1_drug2,直到tiume6_drug5(总共30个文件)。我想将这些xlsx加载到R,并将它们命名为t1d1,t2d2等数据集。 我尝试使用sprintf,但无法弄清楚如何使之有效。

for(i in 1:6) {
  for(j in 1:5) {
sprintf("time%i","drug%j,i,j)=read.xlsx("/Users/pathway/dataset/time_sprintf(%i,i)_drug(%j,j).xlsx", 1)}
names(sprintf("t%i","d%j,i,j))=c("result", "testF","TestN")
sprintf("t%i","d%j,i,j)$Discription[which(sprintf("t%i","d%j,i,j)$testF>=1&sprintf("t%i","d%j,i,j)$TestN>=2)]="High+High"
}
}

我希望能获得t1d1到t6d5之类的30条数据。

2 个答案:

答案 0 :(得分:0)

您应该(几乎)永远不要使用assign。将多个文件读入R时,您应该(几乎)始终将它们放在一个命名列表中。

一个更好的方法的大致概述是:

# Put all the excel files in a directory and this retrieves all their paths
f <- dir("/Users/pathway/dataset/",full.names = TRUE)
# Read all files into a list
drug_time <- lapply(X = f,FUN = read.xlsx)
# Name each list element based on the file name
names(drug_time) <- gsub(pattern = ".xlsx",replacement = "",x = basename(f),fixed = TRUE)

答案 1 :(得分:-1)

您可以直接使用for循环,但也应该使用assign函数:

for(i in 1:6){
for(j in 1:5){
assign(paste0('t', i, '_', 'd', j), read.xlsx(paste0("/Users/pathway/dataset/time_",i,"_drug",j,".xlsx"), 1))
}
}