在 R 中使用 for 循环绑定来自两个数据帧的列的问题

Problems with binding columns from two data frames using a for loop in R

我有两个不同的 asc 文件中的 7 个加载到 R,asc[i]wasc[i][i] 表示有 1:7 ascswascs 加载到 R 中。我需要将 wasc[i]asc[i][[1]] 合并(只是 asc[i] 中的第一列与整个 wasc[i] 文件) .

每对 ascwasc 文件都应重复此操作。

代码一直给我空白数据框,所以我不知道为什么这不起作用。命名是正确的,但代码没有识别出 asc[i]wasc[i] 与先前加载的文件相关联。

任何帮助将不胜感激。

# These data frames will reproduce my issue 

asc1 <- data.frame(x= c(rep("A.tif", 20)), y = 1:20)
wasc1 <- data.frame(x= c(rep("B.tif", 20)), y = c(rep("Imager",20)))

asc2 <- data.frame(x= c(rep("A.tif", 20)), y = 1:20)
wasc2 <- data.frame(x= c(rep("B.tif", 20)), y = c(rep("Imager",20)))

asc3 <- data.frame(x= c(rep("A.tif", 20)), y = 1:20)
wasc3 <- data.frame(x= c(rep("B.tif", 20)), y = c(rep("Imager",20)))


for (i in 1:3) {
      d <- paste("asc", i, sep ="")
      f <- paste("wasc", i, sep ="")
      full_wing <- as.character(paste("full_wing", i, sep = ""))
      assign(full_wing,cbind(d[[1]], f))
    }

# Output of full_wing1 data frame

dput(full_wing1)

structure(c("asc1", "wasc1"), .Dim = 1:2, .Dimnames = list(NULL, 
c("", "f")))

附加信息:

  1. asc 文件有 19 列长
  2. wasc 文件有 13 列长

我只想将 asc 文件的第 1 列与整个 wasc 文件合并,从而删除 asc 文件的剩余 18 列。

# put data in a list
asc = mget(ls(pattern = "^asc"))
wasc = mget(ls(pattern = "^wasc"))

full_wing = Map(f = function(w, a) cbind(w, a[[1]]), w = wasc, a = asc)

Map 是并行迭代多个参数的一个很好的快捷方式。它 returns 不错 list。您可以使用 full_wing[[1]]full_wing[[3]] 等访问各个元素。Map 只是一个快捷方式,上面的代码基本上等同于下面的 for 循环:

results = list()
for (i in seq_along(asc)) {
    results[[i]] = cbind(wasc[[i]], asc[[i]][[1]])
}

我使用 mget 将数据放入列表中,因为在您的示例中您已经拥有 asc1asc2 等对象。更好的方法是永远不要首先创建这些变量,而是直接将文件读入列表,如下所示:

asc_paths = list.files(pattern = "^asc")
asc = lapply(asc_paths, read.table)

你可以在 How to make a list of data frames?

看到更多关于这个的解释

如果您只需要 asc 文件中的一列,另一种简化方法是只读入所需的列,请参阅 Only read limited number of columns 那里的一些建议。