【问题标题】:Using two vectors to loop through code to generate one xlsx output using R使用两个向量循环代码以使用 R 生成一个 xlsx 输出
【发布时间】:2020-04-24 11:23:58
【问题描述】:

我在几个 Excel 数据库中有数据,我想将这些数据合并到一个带有调整信息的 Excel 中。唯一标识符是要加载的 Excel 文件的 ALM 命名,以及大型 Excel 数据库中的 Boog_ID。

我已经编写了下一个代码:

#Import section_id's and corresponding ALM's
section_ids <- read.csv2("section_ids.csv", colClasses = "character")

## Repeat all below for all sections
for (i in section_ids$alm) {
  for (j in section_ids$boog_id) {

#Import excel using "Import dataset" 
hor <- read_xlsx(paste("ALM_", i,".xlsx", sep = ""), 1)
ver <- read_xlsx(paste("ALM_", i,".xlsx", sep = ""), 2)
add_complete <- read_xlsx("curve_information_combined.xlsx")

#Extract correct additional information
add <- filter(add_complete, BoogID == j)

## A bunch of code to generate a dataframe named "combined"  to generate a dataframe per section_id.
## This code works flawless and is therefore left out of this example

#Export as xlsx
write.xlsx(combined, "road_characteristics.xlsx", row.names = FALSE, append = TRUE)
  }
}

我希望生成一个包含所有 section_id 的所有信息的 excel 文件。但是,循环似乎在第一次迭代后卡住了,生成了一个仅包含有关第一个 curve_id 信息的 Excel。 此外,i 没有更新为 section_ids$alm 中的第二个值,但 j 已更新为 section_ids$boog_id 中的第二个值。

我做错了什么?为什么循环不继续?也许是 for 循环中的一个基本错误?我在网上搜索过,但没有找到好的答案。

【问题讨论】:

  • 你好约翰。欢迎来到 StackOverflow。请阅读How to create a minimal, reproducible example 并更新您的问题。正如目前所写的那样,您的问题中没有足够的信息让某人弄清楚为什么循环没有按预期工作。

标签: r excel loops


【解决方案1】:

正如 Len 所提到的,我将尝试给出一个可重现的示例,但我对此不确定...#noob

alm <- c(1, 2, 3, 4, 5, 6)
section_id = c("a", "b", "c", "d", "e", "f")
section_ids <- data.frame(alm, section_id)                          

for (i in section_ids$alm) {
  for (j in section_ids$boog_id) {

#some code
example <- i
test <- j
combined <- merge(example, test)

#Export as xlsx
write.xlsx(combined, "road_characteristics.xlsx", row.names = FALSE, append = TRUE)
  }
}

【讨论】:

    猜你喜欢
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多