R - Combine columns

3226 views r
2

I have a data frame with 2 columns, where they have some overlap values.

data <- data.frame('A' = c(1,2,"",4,5,6),
               'B' = c(1,"",3,4,"",6))

I would to combine these columns into 1 column like C = c(1,2,3,4,5,6)

Thanks

answered question

If you don't mind seeing "" in a vector, try unique(unlist(data))

1 Answer

3

this may not be sufficient to cover the cases you need to address, but may give you a start:

> unlist( str_extract_all( apply(data,1,function(x) unique(x)), "[[:digit:]]+" ) )
[1] "1" "2" "3" "4" "5" "6"

It picks out unique values by row (1) using apply, then extracts all digits, and collapses the multi-level list into a regular list.

posted this

Have an answer?

JD

Please login first before posting an answer.