Search code examples
rlistindexingsubset

In R how to operate in a list with names


This is my list

list_names <- vector(mode = 'list')

list_names[['NAME A']] <- rnorm(n = 10,sd = 2)
list_names[['NAME B']] <- rnorm(n = 10,sd = 2)
list_names[['NAME C']] <- rnorm(n = 10,sd = 2)
list_names[['NAME D']] <- rnorm(n = 10,sd = 2)
list_names[['NAME E']] <- rnorm(n = 10,sd = 2)
list_names[['NAME F']] <- rnorm(n = 10,sd = 2)

Is it possible to select others elements of list doing something like this:

list_names[[-"NAME A"]]

The output should be a list with all elements except the "NAME A" element?


Solution

  • We need [ and not [[ for selecting more than one element from a list. Also, - wouldn't work, instead use setdiff

    list_names[setdiff(names(list_names), "NAME A")]
    

    -output

    $`NAME B`
     [1] -3.237378  4.082310  1.330150  1.784154  1.360302  5.530083 -4.593817 -2.021845 -2.278811  5.359281
    
    $`NAME C`
     [1]  0.7641719 -0.9874008  0.9278225 -0.9709333 -0.1113175 -0.2290865 -0.2682319  2.8789682  0.6797194 -1.8765561
    
    $`NAME D`
     [1]  3.8257606 -3.0235199 -3.4250881 -0.1333553  0.1202357  0.3694179 -2.0254176 -1.9489545  1.1015625  2.5311685
    
    $`NAME E`
     [1]  2.4825388 -0.9485210 -2.7486256 -1.1970403 -1.3655852 -0.4481327 -2.0552594  0.3480588  1.9688285  1.1266358
    
    $`NAME F`
     [1]  2.7535404  1.9831037 -2.3185156  0.5392882  1.0800234 -3.3278948 -1.7413377 -1.9040359  1.2478318  1.2664443
    

    Or another option is a logical vector

    list_names[names(list_names) != "NAME A"]