Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:将输出保存为for循环中的xlsx_R - Fatal编程技术网

R:将输出保存为for循环中的xlsx

R:将输出保存为for循环中的xlsx,r,R,使用(openxlsx)包编写xlsx文件。 我有一个变量,它是一个数字向量 x <- 1:8 当我打开(“1.xlsx”-“8.xlsx”)时,所有文件上都只有数字“8”。我不明白的是,为什么1.xlsx没有数字1,7.xlsx没有数字7,为什么第8个会覆盖其他所有内容 我甚至试着按照大多数人的建议为数据帧创建一个新的输出 for (i in x) { for (j in new_x) { output[[i]] <- i write.xlsx(output[[i]],

使用(openxlsx)包编写xlsx文件。 我有一个变量,它是一个数字向量

x <- 1:8
当我打开(“1.xlsx”-“8.xlsx”)时,所有文件上都只有数字“8”。我不明白的是,为什么1.xlsx没有数字1,7.xlsx没有数字7,为什么第8个会覆盖其他所有内容

我甚至试着按照大多数人的建议为数据帧创建一个新的输出

for (i in x) {
for (j in new_x) {
output[[i]] <- i    

write.xlsx(output[[i]],j)
}}
for(i在x中){
适用于(纽约州的j){

输出[[i]]问题在于,由于存在嵌套循环,因此要多次创建每个Excel文件。请尝试仅使用单个循环,并引用新的\u x元素

x <- 1:8
new_x <- paste(x,".xlsx", sep = "")
for (i in seq_along(x)) {
    write.xlsx(i,new_x[i])
}

x将
print(i)
print(j)
添加到您的循环中,看看当
i=8时会发生什么情况
如果有一个txt文件矢量而不是1:8,我必须读取每个文件的.csv,会怎么样?如果我使用read.csv(i),是否有一个变量我应该将其转换为(再次转换为i?)在forloop中?我还认为这个问题只是通过seq_-along函数暂时解决的。有没有一种方法可以在没有seq_的情况下实现这一点?您可以使用
seq
seq_-len
生成序列。
for (i in x) {
for (j in new_x) {
output[[i]] <- i    

write.xlsx(output[[i]],j)
}}
x <- 1:8
new_x <- paste(x,".xlsx", sep = "")
for (i in seq_along(x)) {
    write.xlsx(i,new_x[i])
}
# Define directory of where to look for csv files and where to save Excel files
csvDirectory <- "C:/Foo/Bar/"
ExcelDirectory <- paste0(Sys.getenv(c("USERPROFILE")),"\\Desktop")

# Find all the csv files of interest
csvFiles <- list.files(csvDirectory,"*.csv")

# Go through the list of files and for each one read it into R, and then save it as Excel
for (i in seq_along(csvFiles)) {
  csvFile <- read.csv(paste0(csvDirectory,"/",csvFiles[i]))
  write.xlsx(csvFile, paste0(ExcelDirectory,"/",gsub("\\.csv$","\\.xlsx",csvFiles[i])))
}