我对R有点新,并试图学习,但我很困惑如何解决我偶然发现的问题。我正在尝试输入多个文件,以便我可以为每个文件制作一个直方图。代码运行良好,特别是只有一个文件,但是当我输入多个文件时遇到了问题。
编辑:结束代码
library("scales")
library("tcltk")
File.names<-(tk_choose.files(default="", caption="Choose your files", multi=TRUE, filters=NULL, index=1))
Num.Files<-NROW(File.names)
dat <- lapply(File.names,read.table,header = TRUE)
names(dat) <- paste("f", 1:length(Num.Files), sep="")
tmp <- stack(lapply(dat,function(x) x[,14]))
require(ggplot2)
ggplot(tmp,aes(x = values)) +
facet_wrap(~ind) +
geom_histogram(aes(y=..count../sum(..count..)))
答案 0 :(得分:5)
嗯,这是让你入门的东西(但是我无法确定它是否适合你,因为你的代码不可复制):
dat <- lapply(File.names,read.table,header = TRUE)
names(dat) <- paste("f", 1:length(Num.Files), sep="")
tmp <- stack(lapply(dat,function(x) x[,14]))
require(ggplot2)
ggplot(tmp,aes(x = values)) +
facet_wrap(~ind) +
geom_histogram()
在这一行之后抛弃你所写的一切:
File.names<-(tk_choose.files(default="", caption="Choose your files", multi=TRUE, filters=NULL, index=1))
并使用上面的代码。
其他一些解释(BlueTrin解释了第一个错误):
for (i in Num.Files){
f<- read.table(File.names[i],header=TRUE)
}
这将遍历您的文件名并读取每个文件名,但每次循环时它都会覆盖上一个文件。您剩下的只是 f
中存储的最后一个文件。
colnames(f) <- c(1:18)
histoCol <- c(f$'14')
此处不需要c()
功能。只需1:18
即可。但是作为列名的数字通常很尴尬,应该避免使用。
答案 1 :(得分:2)
f(Num.Files) <- paste("f", 1:length(Num.Files), sep = "") : could not find function "f<-"
发生此特定错误是因为您尝试将字符串分配给函数的结果。
这应该将值加载到列表中:
library("lattice");
library("tcltk");
File.names<-(tk_choose.files(default="", caption="Choose your files", multi=TRUE, filters=NULL, index=1));
Num.Files<-NROW(File.names);
result_list = list();
#f(Num.Files)<-paste("f", 1:length(Num.Files), sep="");
#ls();
for (i in Num.Files) {
full_path = File.names[i];
short_name = basename(full_path);
result_list[[short_name]] = read.table(full_path,header=TRUE);
}
运行此程序后,您可以在不带引号的情况下键入“result_list $”,然后按TAB键完成。或者,您可以使用result_list [[1]]来访问第一个表。
result_list是类型列表的变量,它是一个支持标签索引的容器,在这种情况下是文件名。 (我用短文件名替换了完整的文件名,因为完整的文件名在列表中有点难看但可以随意改回来。)
小心不要将f用作变量,f是创建函数时的保留关键字。如果您尝试将上面的程序中的result_list替换为f,则它将无法工作。
我希望通过其他解决方案让你开始就足够了!