使用R
问题描述:
以不同变量交互式多文件上传我试图让用户定义要为特定治疗上传多少药物的数据用户。基于这个数字,我的功能是让用户为许多药物选择数据并用变量存储它们。 drug_1_data,drug_2_data等 我已经写了代码,但它不工作 可能有人请帮助使用R
no_drugs <- readline("how many drugs for this therapy? Ans:")
i=0
while(i < no_drugs) {
i <- i+1
caption_to_add <- paste("drug",i, sep = "_")
mydata <- choose.files(caption = caption_to_add) # caption describes data for which drug
file_name <- noquote(paste("drug", i, "data", sep = "_")) # to create variable that will save uploaded .csv file
file_name <- read.csv(mydata[i],header=TRUE, sep = "\t")
}
答
在你的榜样,mydata
是一个元素串,所以用i
子集大于1将返回NA
。此外,在第一次分配file_name
时,将其设置为非引号字符向量,但随后用数据覆盖它(并且在循环的每次迭代中,都会丢失上一步创建的数据)。我想你想要的是更多的东西的行:
file_name <- paste("drug", i, "data", sep = "_")
assign(file_name, read.delim(mydata, header=TRUE)
# I changed the function to read.delim since the separator is a tab
不过,我也建议考虑把所有的数据在一个列表(它可能是更容易申请操作多种药物dataframes像),使用像这样的东西:
n_drugs <- as.numeric(readline("how many drugs for this therapy? Ans:"))
drugs <- vector("list", n_drugs)
for(i in 1:n_drugs) {
caption_to_add <- paste("drug",i, sep = "_")
mydata <- choose.files(caption = caption_to_add)
drugs[i] <- read.delim(mydata,header=TRUE)
}
谢谢。它的工作原理 –
乐意帮忙,欢迎来到Stack Overflow。如果此答案或任何其他人解决了您的问题,请将其标记为已接受。 – Sraffa