Vinodh Velumayil
Vinodh Velumayil

Reputation: 762

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

Upvotes: 5

Views: 33278

Answers (4)

Researchnology
Researchnology

Reputation: 21

A more convenient method can convert a string with any number of words to a list, is to first unlist your "result", then convert that vector to a list:

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

# Then convert result to a list
lapply(unlist(result), function(x) x)
> 
[[1]]
[1] "qwerty"

[[2]]
[1] "keyboard"

Upvotes: 0

Rich Scriven
Rich Scriven

Reputation: 99331

As an alternative to strsplit(), you can make a list out of the result from scan().

as.list(scan(text=str, what=""))
# Read 2 items
# [[1]]
# [1] "qwerty"
#
# [[2]]
# [1] "keyboard"

Upvotes: 0

M. Wall
M. Wall

Reputation: 11

as.list(unlist(strsplit(str, '[[:space:]]')))

Upvotes: 1

NEO
NEO

Reputation: 441

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]])

Upvotes: 18

Related Questions