Home > other >  How to drop strings in a character vector when the vector is part of a list in R?
How to drop strings in a character vector when the vector is part of a list in R?

Time:11-18

I have a list object like the following:

list_data <- list("Red", "Green", c("Purple", "Yellow"), "Orange", c("Black","White"))

I would like to drop the second observations in every character vector to get an output like this `

print(list_data)`

"Red, Green, Purple, Orange, Black"

So I am trying to drop the second observations that are Yellow and White. How do I do it? Please note that it is a large list so I can not do it manually.

CodePudding user response:

Just extract the first with indexing

lapply(list_data, `[`, 1) #if we need a list output
# or if we need a vector, use sapply
sapply(list_data, `[`, 1)
[1] "Red"    "Green"  "Purple" "Orange" "Black" 
# if it should be a single string
toString(sapply(list_data, `[`, 1))
[1] "Red, Green, Purple, Orange, Black"

CodePudding user response:

Using purrr:

library(purrr)

list_data <- list(
  "Red",
  "Green",
  c("Purple", "Yellow"),
  "Orange",
  c("Black","White")
) 

map(list_data, ~ .x[1])
# [[1]]
# [1] "Red"
# 
# [[2]]
# [1] "Green"
# 
# [[3]]
# [1] "Purple"
# 
# [[4]]
# [1] "Orange"
# 
# [[5]]
# [1] "Black"

# Or to get a vector:
map_chr(list_data, ~ .x[1])
# [1] "Red"    "Green"  "Purple" "Orange" "Black" 

# Or to get a string:
reduce(list_data, ~ paste(.x, .y[1], sep = ", "))
# [1] "Red, Green, Purple, Orange, Black"
  • Related