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?
CodePudding user response:
Probably this is what you are after
list_names[-match('NAME A',names(list_names))]
!! WARNING: if the requested name is not a valid name of list_names
, then the solution will return NULL
(thanks for @akrun's comment)
CodePudding user response:
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"]
CodePudding user response:
You can negate %in%
and provide a vector of names to exclude which will work with any number of names. This also tolerates names that are not members of names(l)
without returning an error.
l <- list(a = 1:3,
b = 1:3,
c = 1:3)
exclude_names <- "a"
l[!names(l) %in% exclude_names]
#> $b
#> [1] 1 2 3
#>
#> $c
#> [1] 1 2 3
Created on 2022-11-21 with reprex v2.0.2
CodePudding user response:
Another option is using purrr
After identifying NAME A
we could zap
it:
purrr::list_modify(list_names,`NAME A`=purrr::zap())
$`NAME B`
[1] -0.8390912 1.3642602 0.5660608 -0.9540717 -0.3867816 -0.2885152 2.2319706 -1.3307411 -1.6760324 1.2665064
$`NAME C`
[1] -2.2107425 2.2710206 1.9398283 0.8652335 1.7688116 0.4958797 -0.6015274 1.3835770 3.7064383 0.8566645
$`NAME D`
[1] 0.59945041 -2.35641913 0.58695111 0.42641701 1.16167489 0.05766859 1.37930744 0.18369875 0.62319538
[10] -0.36985800
$`NAME E`
[1] 4.197209 -3.543006 2.558110 3.378172 -2.749093 1.549671 -1.237776 4.361019 1.611182 -1.038159
$`NAME F`
[1] -0.3487643 1.0043091 -0.5399112 1.0901489 0.5731137 -1.2881900 1.0738251 1.8890504 1.0534804 0.4025011