简体   繁体   English

如何在R for循环中保存几个数据帧

[英]How to save several dataframes in a R for loop

What I want to do is save one y dataframe for each file in the loop below.Right now, I only have the last one. 我要做的是在下面的循环中为每个文件保存一个y数据帧。现在,我只有最后一个。

temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.csv)

for (file in myfiles){
 y <- some code
}

y has 26 observations of 2 variables. y有2个变量的26个观测值。

Sorry if this is not a working example. 抱歉,如果这不是一个可行的示例。 My data is too big even if taking samples. 即使取样,我的数据也太大。 Any help is much appreciated. 任何帮助深表感谢。

df <- do.call("rbind",lapply(list.files(pattern = "*.csv"),read.csv, header = TRUE))

这是一个例子

If I understand well, you want to save y as a csv ? 据我了解,您想将y另存为csv吗? You could do something like this: 您可以执行以下操作:

temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.csv)
## Adding a counter to be incremented in the loop
counter <- 1

for (file in myfiles){
 y <- some code
 ## writing the csv
 write.csv(y, file = paste0("my_csv_", counter, ".csv")
 ## Increment the counter
 counter <- counter + 1
}

Or do you want to save y as a variable containing all your data.frames? 还是要将y保存为包含所有data.frames的变量? In this case, you can do something like this: 在这种情况下,您可以执行以下操作:

temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.csv)
## Adding a counter to be incremented in the loop
counter <- 1
## Create an empty list y

for (file in myfiles){
 y[[counter]] <- some code
 ## Increment the counter
 counter <- counter + 1
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM