incorrect number of subscripts on matrix in R -
so, have list of data frames, named "d1.txt", "d2.txt"................"d45.txt". each of file contains
2 columns , each file has 1000's of rows`.
i trying add new column each of data frame in list, following code, shows error incorrect number of subscripts on matrix
.
the code using is,
l <- lapply(seq_along(l), function(i) { l[[i]][, paste0('df', i)] <- 1 l[[i]] })
where l
name of list containing data frames.
why error coming? thanks! :)
edit: reprdoucible example:
# create dummy data l <- replicate(5, expand.grid(1:10, 1:10)[sample(100, 10), ], simplify=false) # add column each data.frame in l. # indicate presence of pair when merge. l <- lapply(seq_along(l), function(i) { l[[i]][, paste0('df', i)] <- 1 l[[i]] })
i think when read in "d1.txt", "d2.txt"................"d45.txt"
files converted matrices , why particular loop fails. i'll use example:
l <- replicate(5, expand.grid(1:10, 1:10)[sample(100, 10), ], simplify=false)
if use class(l[[1]])
pick out first element of list output [1] "data.frame"
if use loop on list contains data.frames
see no error , give want. if transform elements in list matrices:
for(i in seq_along(l)){ l[[i]] <- as.matrix(l[[i]]) }
and check class(l[[1]])
output [1] "matrix"
. if use loop on l
contains matrices get:
> 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
hence, can either make sure when read in files coerced data.frames
, use @richards solution, or read in files , coerce them data.frames
via
for(i in seq_along(l)){ l[[i]] <- as.data.frame(l[[i]]) }
and use loop.
Comments
Post a Comment