Invalid number of indices on matrix in R

So, I have a list of data frames named as "D1.txt", "D2.txt"................"D45.txt". Each of the file contains "D1.txt", "D2.txt"................"D45.txt". Each of the file contains 2 columns, and each file has 1000 lines`.

Basically, I am trying to add a new column to each of the data frames in the list with the following code, but it shows the error as incorrect number of subscripts on matrix .

The code I'm using is

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

where L is the name of the list containing data frames.

Why does this error occur? Thank you :)

Edit: an option that can be called valid:

 # 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]] }) 
+6
source share
2 answers

I think that when you read "D1.txt", "D2.txt"................"D45.txt" in your files "D1.txt", "D2.txt"................"D45.txt" , they are converted to matrices, and therefore your particular for loop is not working. I will use your example:

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

If we use class(L[[1]]) to select the first element of the list, it will output [1] "data.frame" , if you use a for loop in this list that contains only data.frames , you will not see an error. and it will give you what you want. If, however, we convert all the elements into a list into matrices:

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

and using class(L[[1]]) it will output [1] "matrix" . If you use the for for loop now on L , which now contains matrices, we 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 

Therefore, you can either make sure that when you read in your files, they are forced to data.frames , use the @Richards solution or read in your files and force them to data.frames via

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

and use the for loop.

+6
source

Here is a small example of how to add columns to data frames stored in a list. Use [<- with your lapply call to assign a new column. Here I add the column "newCol" , which contains the values ​​10 and 11, to each data frame in 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 
+2
source

Source: https://habr.com/ru/post/973969/


All Articles