【问题标题】:Loop through individual data frames and add new column [duplicate]循环遍历各个数据框并添加新列[重复]
【发布时间】:2014-10-19 18:46:15
【问题描述】:

我想遍历单个数据框(不在列表中)并向每个 df 附加一列,以便附加的列是原始 df 中第一列的副本。

对于 df x:

> x
  V1 V2 V3
1  1  2  3
2  1  2  3
3  1  2  2
4  1  2  2
5  1  1  1

期望的输出是:

> x
  V1 V2 V3 newCol
1  1  2  3  1
2  1  2  3  1
3  1  2  2  1
4  1  2  2  1
5  1  1  1  1

我尝试使用这个循环:

filenames <- names(which(sapply(.GlobalEnv, is.data.frame)))
for(x in seq_along(filenames)){
  filenames[x]$newCol  <-   x[,1]
}

但出现错误:

x[, 1] 中的错误:维数不正确

【问题讨论】:

  • 好的,看来您知道它们应该在列表中。将它们放入列表中。
  • @RichardScriven 该答案确实解决了我遇到的问题,但我认为这不是重复的,因为最初的问题是关于专门使用 for 循环执行此操作。无论如何,我意识到这不是一种非常 R 的方式。 :-)

标签: r loops assign


【解决方案1】:

像这样:

给变量文件名[x] 赋值,该值是第一列的数据框:)

assign(filenames[x], data.frame(get(filenames[x]),get(filenames[x])[,1]))

【讨论】:

  • 这没有回答问题。
  • @Roland 现在可以了 :)
  • @bartektartanus 感谢您的回答。
【解决方案2】:

或者,你可以写

   for(i in seq_along(filenames)){
    assign(filenames[i], `[[<-`(get(filenames[i]),'newCol', 
                                value=get(filenames[i])[,1]))
   }

与下面的类似:

   for(i in seq_along(filenames)) {
   x <- get(filenames[i])
   x$newCol <- x[, 1]
   assign(filenames[i], x)
  }

  x1
 #  V1 V2 V3 newCol
 #1  1  2  3      1
 #2  1  2  3      1
 #3  1  2  2      1
 #4  1  2  2      1
 #5  1  1  1      1

上面也可以写成:

数据

  x1 <- structure(list(V1 = c(1L, 1L, 1L, 1L, 1L), V2 = c(2L, 2L, 2L, 
  2L, 1L), V3 = c(3L, 3L, 2L, 2L, 1L)), .Names = c("V1", "V2", 
 "V3"), class = "data.frame", row.names = c("1", "2", "3", "4", 
  "5"))

  x2 <- x1

  filenames <- c("x1", "x2")

【讨论】:

  • 前几天我们不是刚刚回答了这个问题吗? :-)
  • @Richard Sciven 有点不同。我认为这是通过将数据集的名称附加到列的名称来更改列的名称。
猜你喜欢
  • 2018-03-16
  • 1970-01-01
  • 2018-10-16
  • 2021-10-11
  • 2019-08-07
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多