Doug Fir
Doug Fir

Reputation: 21204

convert text sentences to a comma separated vector

I have a dataframe x:

> x
        id type
1 13159355  traffic s
2 13159356 suspicious
3 13159357      crash
4 13159358  traffic s
5 13159359    parking
6 13159360  traffic s

I would like to make each row of x$type be a vector so that, for example, x[1,2] would return "traffic", "s" just like if I did c("traffic", "s")

Tried:

> x$type <- gsub("\\s", ", ", x$type)
> x
        id type
1 13159355 traffic, s
2 13159356 suspicious
3 13159357      crash
4 13159358 traffic, s
5 13159359    parking
6 13159360 traffic, s

But if I select x[1,2] a single string is returned and not a chr vector.

How can I change all sentences in x$type to be a chr vector or words?

Upvotes: 1

Views: 43

Answers (1)

akrun
akrun

Reputation: 886968

Based on the description, it seems the OP wanted a list column. For this, we can split the column 'type' by one or more spaces (\\s+)

x$type <- strsplit(x$type, "\\s+")
x[1,2][[1]]
#[1] "traffic" "s"     

Upvotes: 1

Related Questions