Search code examples
r

String Split into list R


Extract words from a string and make a list in R

str <- "qwerty keyboard"
result <- strsplit(str,"[[:space:]]")

What I get was..(down below)

result
[[1]]
[1] "qwerty" "keyboard"

What I need is..(down below)

result
[[1]]
[1] "qwerty"
[[2]]
[1] "keyboard"

[OR]

result
[[1]]
[1] "qwerty"
[2] "keyboard"

I am looking for a solution, if someone knows please post your solution here. thanks in advance..


Solution

  • try:

    str <- "qwerty keyboard"
    result_1 <- strsplit(str,"[[:space:]]")[[1]][1]
    result_2 <- strsplit(str,"[[:space:]]")[[1]][2]
    result <- list(result_1,result_2)
    

    Or

    as.list(strsplit(str, '\\s+')[[1]])