Drick
Drick

Reputation: 57

How could I split a nested list using str_split without the use of for loop?

Now I have a nested list containing something like this

[[1]] [1] "53" "682, 684" "677" "683"

[[2]] [1] "40, 43" "10" "44, 47"

and I want to split each list by ", " so that they can all be a list of numbers into

[[1]] [1] "53" "682" "684" "677" "683"

[[2]] [1] "40" "43" "10" "44" "47"

Now my current idea is I want to use apply() and define my own function using recursion, but how to detect there is how many lists in each row?

I'm required not to use for loop, so what should I do??

Upvotes: 0

Views: 219

Answers (1)

Wimpel
Wimpel

Reputation: 27732

something like this? not sure since the format of the sample data in the question is unknown...

#create sample data
v1 <- c("53", "682, 684", "677", "683")
v2 <- c("40, 43", "10", "44, 47")
l <- list( v1, v2 )

#code
lapply( l, function(x) trimws( unlist ( strsplit( x, ",") ) ) )

#output
# [[1]]
# [1] "53"  "682" "684" "677" "683"
# 
# [[2]]
# [1] "40" "43" "10" "44" "47"
# 

Upvotes: 1

Related Questions