Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenate values across two rows in R

I am trying to concatenate two rows from a data frame in R with a similar format

row1 <- c("A","B","C")
row2 <- c(1:3)
dat <- data.frame(rbind(row1,row2))
dat
     X1 X2 X3
row1  A  B  C
row2  1  2  3

I would like third row of the type

row3 A-1 B-2 C-3

Can someone help me to do this using the paste function? I have been trying the following without success:

> paste(dat[1,], dat[2,], sep="-")
[1] "2-1" "2-1" "2-1"
> paste(as.character(dat[1,]), dat[2,], sep="-")
[1] "2-1" "2-1" "2-1"

Thanks in advance!

like image 553
ZMacarozzi Avatar asked Sep 15 '25 02:09

ZMacarozzi


2 Answers

Here's one approach:

rbind(dat, row3 = apply(dat, 2, paste0, collapse = "-"))
#      X1  X2  X3
#row1   A   B   C
#row2   1   2   3
#row3 A-1 B-2 C-3

Provided that you have taken the necessary steps to avoid using factors, i.e.

row1 <- c("A","B","C")
row2 <- as.character(1:3)
dat <- data.frame(
  rbind(row1, row2), 
  stringsAsFactors = FALSE
)
like image 157
nrussell Avatar answered Sep 16 '25 20:09

nrussell


One option with data.table

library(data.table)
rbindlist(list(dat, setDT(dat)[, lapply(.SD, paste, collapse='-')]))
#    X1  X2  X3
#1:   A   B   C
#2:   1   2   3
#3: A-1 B-2 C-3
like image 40
akrun Avatar answered Sep 16 '25 20:09

akrun