【问题标题】:Adding new columns and column names in a loop in R在 R 中的循环中添加新列和列名
【发布时间】:2023-03-04 09:52:02
【问题描述】:

我有一个循环读取一系列 .csv 文件

for (i in 1:3)
{
  nam <- paste0("A_tree", i)
  assign(nam, read.csv(sprintf("/Users/sethparker/Documents/%d_tree_from_data.txt", i), header = FALSE))
}

这可以正常工作并生成一系列与此示例数据相当的文件

A_tree1 <- data.frame(cbind(c(1:5),c(1:5),c(1:5)))
A_tree2 <- data.frame(cbind(c(2:6),c(2:6),c(2:6)))
A_tree3 <- data.frame(cbind(c(3:10),c(3:10),c(3:10)))

我想要做的是添加列名,并用数据填充 2 个新列(月份和模型运行)。我目前成功的方法是单独执行此操作,如下所示:

colnames(A_tree1) <-  c("GPP","NPP","LA")
A_tree1$month <- seq.int(nrow(A_tree1))
A_tree1$run <- c("1")
colnames(A_tree2) <-  c("GPP","NPP","LA")
A_tree2$month <- seq.int(nrow(A_tree2))
A_tree2$run <- c("2")
colnames(A_tree3) <-  c("GPP","NPP","LA")
A_tree3$month <- seq.int(nrow(A_tree3))
A_tree3$run <- c("3")

这对于我拥有的_tree 对象的数量来说是非常低效的。尝试使用paste0()sprintf() 修改循环以合并这些所需的操作导致Error: target of assignment expands to non-language object。我想我理解为什么在阅读其他帖子 (Error in <my code> : target of assignment expands to non-language object) 后会出现此错误。是否可以在我的 for 循环中做我想做的事情?如果没有,我怎样才能更好地自动化呢?

【问题讨论】:

    标签: r dataframe for-loop


    【解决方案1】:

    你可以使用lapply:

    n <- index #(include here the total index)
    l <- lapply(1:n, function(i) {
      # this is the same of sprintf, but i prefer paste0
      # importing data on each index i
      r <- read.csv(
        paste0("/Users/sethparker/Documents/", i, "_tree_from_data.txt"), 
        header = FALSE
      )
      
      # creating add columns
      r$month <- seq.int(nrow(r))
      r$run <- i
      
      return(r)
    })
    
    # lapply will return a list for you, if you desire to append tables
    # include a %>% operator and a bind_rows() call (dplyr package)
    l %>%
      bind_rows() # like this
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-10
      • 2021-07-10
      • 1970-01-01
      • 1970-01-01
      • 2016-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多