user3091668
user3091668

Reputation: 2310

Unique rows based on a specific column containing multiple strings

I would like to split my data.frame, all, into unique rows based on the value column:

all dataframe:

seq  start  value
ch1   20    "NE001", "NE002"
ch2   30    "NE002", "NE003"
ch3   40    "NE001", "NE002", "NE003"

My expected output:

seq  start  value
ch1   20    NE001
ch1   20    NE002
ch2   30    NE002
ch2   30    NE003
ch3   40    NE001
ch3   40    NE002
ch3   40    NE003

Any ideas? Thank you!

Upvotes: 0

Views: 97

Answers (1)

jbaums
jbaums

Reputation: 27388

Here's one slightly fiddly way to achieve it.

d <- data.frame(seq=c('ch1', 'ch2', 'ch3'),
                start=c(20, 30, 40),
                value=c('"NE001", "NE002"',
                        '"NE002", "NE003"',
                        '"NE001", "NE002", "NE003"'))

# sub out quotes and split values into vectors
v <- strsplit(gsub('"', '', d$value), ', ')  

cbind(d[rep(seq_along(v), sapply(v, length)), 1:2], 
      value=unlist(v))

#     seq start value
# 1   ch1    20 NE001
# 1.1 ch1    20 NE002
# 2   ch2    30 NE002
# 2.1 ch2    30 NE003
# 3   ch3    40 NE001
# 3.1 ch3    40 NE002
# 3.2 ch3    40 NE003

Remove row.names as required.

Upvotes: 2

Related Questions