Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Split into list R

Tags:

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..

like image 475
Vinodh Velumayil Avatar asked Dec 02 '22 14:12

Vinodh Velumayil


2 Answers

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]])
like image 161
NEO Avatar answered Jan 04 '23 05:01

NEO


as.list(unlist(strsplit(str, '[[:space:]]')))
like image 42
M. Wall Avatar answered Jan 04 '23 07:01

M. Wall