简体   繁体   中英

Drop column in a list with R

Sample data:

list.data <- list(matrix(seq(1,30,2),5,3),matrix(seq(1,10,2),5,2))

I would like to drop first column of the matrix in the list, but keep the proceeding columns vertically. (as [1:n,1] matrix)

This is what I have tried (and otherwise):

lapply(list.data, function(x) x[,2:ncol(x)])

but the initial 2 column matrix keeps flipping into horizontal position.

What I would like to have is this:

    [[1]]
    [,1] [,2]
[1,]   11   21
[2,]   13   23
[3,]   15   25
[4,]   17   27
[5,]   19   29

    [[2]]
    [,1]
 [1] 1 
 [2] 3 
 [3] 5 
 [4] 7 
 [5] 9

Just add drop = FALSE to your command to keep the dimension attribute intact.

> lapply(list.data, function(x) x[,2:ncol(x), drop = FALSE])
[[1]]
     [,1] [,2]
[1,]   11   21
[2,]   13   23
[3,]   15   25
[4,]   17   27
[5,]   19   29

[[2]]
     [,1]
[1,]    1
[2,]    3
[3,]    5
[4,]    7
[5,]    9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM