Carol.Kar
Carol.Kar

Reputation: 5355

Convert data frame to one cell vector(s)

I would like to convert the columns from a dataframe into one cell.

Currently I am getting the following:

beruf <- c(" 2", " 3", " 5", NA, "aa", "bb", "cc", NA)
contact <- c(" 2", NA, NA, NA, "aa", NA, "ccda", NA)

beruf     <- as.vector(as.matrix(beruf))
contact     <- as.vector(as.matrix(contact))

# append to data frame
df.buffer <- data.frame(as(beruf, "character"), as(contact, "character"))

My Output is like that:

enter image description here

However, I would like to get the following:

enter image description here

Any suggestions how to get the desired output?

I appreciate your replies!

Upvotes: 2

Views: 238

Answers (1)

Chriss Paul
Chriss Paul

Reputation: 1101

You can try in base:

sapply(df.buffer, paste, collapse = ",")

or a little longer in data.table:

setDT(df.buffer)[,lapply(.SD, paste, collapse = ",")]

Upvotes: 1

Related Questions