我有58个数据命名为:h5,h6,... h64。 我想一次在所有这些脚本上运行以下脚本,并将结果保存为1 新数据文件。这是我的剧本:
t <- read.table("h5",header = F, row.names=1)
cor(t)
(cor(t))^2
lm(t$V3 ~ t$V2, data=t)
我知道我可以立即阅读所有数据文件:
myFiles <- list.files(pattern="h.*")
但其余的我不知道如何制作循环或如何将结果存储在新的数据框中。有什么建议吗?
我在输入文件结构下面显示:
HO840M3000540481 993.38 1543.1765
HO840M3000540483 -0.51 1120.8224
HO840M3000540497 1192.06 1651.3322
HO840M3004672697 388.5 1140.0917
HO840M3004672704 426.9 836.3676
HO840M3006005895 524.65 1301.8218
HO840M3006972816 1673.99 1389.1919
HO840M3006988837 188.35 385.6415
HO840M3006988891 2987.58 1919.2762
HO840M3006989113 1097.59 1746.4724
HO840M3007701817 1320.5 1058.4915
HO840M3007701858 -372.15 1090.6167
HO840M3007815980 548.58 759.3870
答案 0 :(得分:1)
这是在黑暗中拍摄的......
myFiles <- paste0("h", 5:64)
all <- lapply(myFiles, read.table, header=F, row.names=1)
t1 <- lapply(all, cor)
t2 <- lapply(all, function(x) (cor(x))^2)
all.lm <- lapply(all, function(x)lm(V3 ~ V2, data=x))
编辑: 根据提供的数据结构,我无法重现评论中提到的错误。请参阅下面的执行。
请详细说明您面临的具体错误。
dat <- structure(list(V2 = c(993.38, -0.51, 1192.06, 388.5, 426.9, 524.65,
1673.99, 188.35, 2987.58, 1097.59, 1320.5, -372.15, 548.58),
V3 = c(1543.1765, 1120.8224, 1651.3322, 1140.0917, 836.3676,
1301.8218, 1389.1919, 385.6415, 1919.2762, 1746.4724, 1058.4915,
1090.6167, 759.387)), .Names = c("V2", "V3"), class = "data.frame", row.names = c("HO840M3000540481",
"HO840M3000540483", "HO840M3000540497", "HO840M3004672697", "HO840M3004672704",
"HO840M3006005895", "HO840M3006972816", "HO840M3006988837", "HO840M3006988891",
"HO840M3006989113", "HO840M3007701817", "HO840M3007701858", "HO840M3007815980"
))
all <- list(dat)
lapply(all, cor)
[[1]]
V2 V3
V2 1.0000000 0.6741098
V3 0.6741098 1.0000000
lapply(all, function(x) (cor(x))^2)
[[1]]
V2 V3
V2 1.0000000 0.4544241
V3 0.4544241 1.0000000
lapply(all, function(x)lm(V3 ~ V2, data=x))
[[1]]
Call:
lm(formula = V3 ~ V2, data = x)
Coefficients:
(Intercept) V2
943.3531 0.3354