Hello,
I have this example below which is working but I feel like there needs to be a cleaner way to do with purrr
or map
or something. Any idea how to get the same output?
L1 <-list(a = list(c(1:5,NA,NA),NA,c(NA,6:10)),
b = list(c(1:5,NA,NA),NA,c(NA,6:10)))
lapply(L1, function(x) {
sapply(x,simplify = FALSE, function(y){
replace(y,is.na(y),"")
}
)
})
#> $a
#> $a[[1]]
#> [1] "1" "2" "3" "4" "5" "" ""
#>
#> $a[[2]]
#> [1] ""
#>
#> $a[[3]]
#> [1] "" "6" "7" "8" "9" "10"
#>
#>
#> $b
#> $b[[1]]
#> [1] "1" "2" "3" "4" "5" "" ""
#>
#> $b[[2]]
#> [1] ""
#>
#> $b[[3]]
#> [1] "" "6" "7" "8" "9" "10"
Created on 2021-06-25 by the reprex package (v2.0.0)
library(tidyverse)
# L1 is a little weird because it's lists within a list
# therefore we need a nested map
L1 <-list(a = list(c(1:5,NA,NA),NA,c(NA,6:10)),
b = list(c(1:5,NA,NA),NA,c(NA,6:10)))
L1
#> $a
#> $a[[1]]
#> [1] 1 2 3 4 5 NA NA
#>
#> $a[[2]]
#> [1] NA
#>
#> $a[[3]]
#> [1] NA 6 7 8 9 10
#>
#>
#> $b
#> $b[[1]]
#> [1] 1 2 3 4 5 NA NA
#>
#> $b[[2]]
#> [1] NA
#>
#> $b[[3]]
#> [1] NA 6 7 8 9 10
map(L1, map, replace_na, "")
#> $a
#> $a[[1]]
#> [1] "1" "2" "3" "4" "5" "" ""
#>
#> $a[[2]]
#> [1] ""
#>
#> $a[[3]]
#> [1] "" "6" "7" "8" "9" "10"
#>
#>
#> $b
#> $b[[1]]
#> [1] "1" "2" "3" "4" "5" "" ""
#>
#> $b[[2]]
#> [1] ""
#>
#> $b[[3]]
#> [1] "" "6" "7" "8" "9" "10"
# you might have intended for it just to be vectors like this:
L2 <-list(a = c(c(1:5,NA,NA),NA,c(NA,6:10)),
b = c(c(1:5,NA,NA),NA,c(NA,6:10)))
L2
#> $a
#> [1] 1 2 3 4 5 NA NA NA NA 6 7 8 9 10
#>
#> $b
#> [1] 1 2 3 4 5 NA NA NA NA 6 7 8 9 10
map(L2, replace_na, "")
#> $a
#> [1] "1" "2" "3" "4" "5" "" "" "" "" "6" "7" "8" "9" "10"
#>
#> $b
#> [1] "1" "2" "3" "4" "5" "" "" "" "" "6" "7" "8" "9" "10"
Created on 2021-06-25 by the reprex package (v1.0.0)
1 Like
Thank you It turned out way simpler than expected. The intention was list of lists.
1 Like
system
Closed
July 2, 2021, 2:34pm
4
This topic was automatically closed 7 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.