MayaGans
MayaGans

Reputation: 1845

Use map to return NA when element missing from nested list

I have a nested list:

test <- list(
  one = list(text = "String", number = "1"),
  two = list(text = "String"),
  three = list(text = "String", number = "3")
)

And I can use map_chr(test, "text") to return every text value, but how would I get map_chr(test, "number") to work and return:

one  two  three
"1"  NA   "3"

Upvotes: 3

Views: 537

Answers (2)

akrun
akrun

Reputation: 887691

We can also use a logical condition

library(purrr)
map_chr(test, ~ {val <- .x$number; replace(val, is.null(val), NA) })
#  one   two three 
#  "1"    NA   "3" 

Upvotes: 0

tmfmnk
tmfmnk

Reputation: 40161

You can do:

map_chr(test, ~ pluck(., "number", .default = NA_character_))

  one   two three 
  "1"    NA   "3" 

Or directly (suggested by @aosmith):

map_chr(test, "number", .default = NA_character_)

Upvotes: 3

Related Questions