R中矩阵的下标数不正确

use*_*242 11 r

所以,我有一个数据框列表,命名为"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]] 
})
Run Code Online (Sandbox Code Playgroud)

where 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]] 
})
Run Code Online (Sandbox Code Playgroud)

lor*_*age 9

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

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

如果我们class(L[[1]])用来挑选列表的第一个元素,[1] "data.frame"如果你在这个列表中使用你的for循环只会包含data.frames你将看到没有错误它会输出你想要的东西.但是,如果我们将列表中的所有元素转换为矩阵:

for(i in seq_along(L)){
     L[[i]] <- as.matrix(L[[i]])
}
Run Code Online (Sandbox Code Playgroud)

并检查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
Run Code Online (Sandbox Code Playgroud)

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

 for(i in seq_along(L)){
    L[[i]] <- as.data.frame(L[[i]])
}
Run Code Online (Sandbox Code Playgroud)

并使用你的for循环.