【问题标题】:incorrect number of subscripts on matrix in RR中矩阵上的下标数量不正确
【发布时间】:2019-11-15 10:29:09
【问题描述】:

所以,我有一个数据框列表,命名为 "D1.txt", "D2.txt"................"D45.txt". Each of the file contains2 列,每个文件有 1000 行。

我正在尝试通过以下代码向列表中的每个数据框添加一个新列,但它显示错误为 incorrect number of subscripts on matrix.

我使用的代码是,

L <- lapply(seq_along(L), function(i) { 
    L[[i]][, paste0('DF', i)] <-  1
    L[[i]] 
})

其中L 是包含数据框的列表的名称。

为什么会出现这个错误?谢谢! :)

编辑:一个可重现的例子:

# Create dummy data
L <- replicate(5, expand.grid(1:10, 1:10)[sample(100, 10), ], simplify=FALSE)

# Add a column to each data.frame in L. 
# This will indicate presence of the pair when we merge.
L <- lapply(seq_along(L), function(i) { 
  L[[i]][, paste0('DF', i)] <-  1
  L[[i]] 
})

【问题讨论】:

  • 一个可重现的小例子会很好。
  • 我应该上传一些文件的样本吗?
  • 谢谢!它在我的机器上运行没有错误...
  • 不,我给出的示例运行良好。但是,当我对我的文件执行此操作时,它会出现这些错误。
  • http://stackoverflow.com/questions/24280263/merging-multiple-text-files-in-r-with-a-constraint。请参阅此中的第一个答案。我说的是这个。

标签: r


【解决方案1】:

我认为当您读取 "D1.txt", "D2.txt"................"D45.txt" 文件时,它们会转换为矩阵,这就是您的特定 for 循环失败的原因。我会用你的例子:

L <- replicate(5, expand.grid(1:10, 1:10)[sample(100, 10), ], simplify=FALSE)

如果我们使用class(L[[1]]) 来选择列表的第一个元素,它将输出[1] "data.frame" 如果您在此列表上使用仅包含data.frames 的for 循环,您将不会看到任何错误,它会给您什么你要。但是,如果我们将列表中的所有元素转换为矩阵:

for(i in seq_along(L)){
     L[[i]] <- as.matrix(L[[i]])
}

并检查class(L[[1]]),它将输出[1] "matrix"。如果你现在在 L 上使用你的 for 循环,它现在包含我们将得到的矩阵:

> L <- lapply(seq_along(L), function(i) { 
+   L[[i]][, paste0('DF', i)] <-  1
+     L[[i]] 
+     })
Error in `[<-`(`*tmp*`, , paste0("DF", i), value = 1) : 
  subscript out of bounds

因此,您可以确保在读入文件时将它们强制转换为data.frames,使用@Richards 解决方案,或者读入文件并通过

将它们强制转换为data.frames
 for(i in seq_along(L)){
    L[[i]] <- as.data.frame(L[[i]])
}

并使用你的 for 循环。

【讨论】:

  • 完美运行。非常感谢。 :)
  • 我认为矩阵强制来自L[[i]][, paste0('DF', i)] &lt;- 1这一行。它应该是L[[i]][paste0('DF', i)] &lt;- 1,因为所有L 元素都是数据帧。看sapply(L, class)的结果
【解决方案2】:

这是一个关于如何向存储在列表中的数据框添加列的小示例。使用 [&lt;- 和您的 lapply 调用来分配新列。在这里,我将包含值 10 和 11 的列 "newCol" 添加到 lst 中的每个数据框

> lst <- list(a = data.frame(x = 1:2), b = data.frame(y =3:4))
> lapply(lst, `[<-`, ,'newCol', 10:11)
# $a
# x  newCol
# 1 1      10
# 2 2      11
# 
# $b
# y  newCol
# 1 3      10
# 2 4      11

【讨论】:

    猜你喜欢
    • 2016-04-27
    • 2017-02-20
    • 2020-03-05
    • 2021-01-05
    • 2021-11-07
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多