Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paste column values together in a data frame

Tags:

r

I am trying to paste together the rowname along with the data in the desired column. I wrote the following code but somehow couldnot find a way to do it correctly.

The desired output will be: "a,1,11" "b,2,22" "c,3,33"

x = data.frame(cbind(f1 = c(1,2,3), f2 = c(5,6,7), f3=c(11,22,33)), row.names= c('a','b','c'))
x
#   f1 f2 f3
# a  1  5 11
# b  2  6 22
# c  3  7 33
do.call("paste", c(rownames(x), x[c('f1','f3')], sep=","))
# [1] "a,b,c,1,11" "a,b,c,2,22" "a,b,c,3,33"
like image 406
learner Avatar asked Apr 12 '26 05:04

learner


1 Answers

Two main points:

  1. Use apply instead of do.call(paste, .)
  2. Use cbind instead of c in this case.
    • If you would rather use c, you would need to coerce the row names to a list or column first, eg: c(list(rownames(x)), x)

Try the following:

 apply(cbind(rownames(x), x[c('f1','f3')]), 1, paste, collapse=",")

       a        b        c 
"a,1,11" "b,2,22" "c,3,33" 
like image 71
Ricardo Saporta Avatar answered Apr 15 '26 00:04

Ricardo Saporta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!