Hi fam,
I need to retrieve all items in paths list that have a length of 4.
e.g length(paths[[3]])
=4
Hi fam,
I need to retrieve all items in paths list that have a length of 4.
e.g length(paths[[3]])
=4
Here is one method.
paths <- list(c("A", "S", "D"), c("Z", "X", "C", "V"), c("W"),
c("W", "E", "R", "T"))
LENGTHS <- sapply(paths,length)
paths[LENGTHS==4]
#> [[1]]
#> [1] "Z" "X" "C" "V"
#>
#> [[2]]
#> [1] "W" "E" "R" "T"
Created on 2022-06-25 by the reprex package (v2.0.1)
R base has a Filter
function for filtering lists and vectors.
With paths
as it is defined in FJCC's post,
paths <- list(c("A", "S", "D"), c("Z", "X", "C", "V"), c("W"), c("W", "E", "R", "T"))
Filter(function(x) length(x) == 4, paths)
See ?Filter
for details.
And then there is keep from {purrr}
library(purrr)
paths <- list(c("A", "S", "D"), c("Z", "X", "C", "V"), c("W"), c("W", "E", "R", "T"))
keep(paths, ~length(.x) == 4)
#> [[1]]
#> [1] "Z" "X" "C" "V"
#>
#> [[2]]
#> [1] "W" "E" "R" "T"
Created on 2022-06-29 by the reprex package (v2.0.1)
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.