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!
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 factor
s, i.e.
row1 <- c("A","B","C")
row2 <- as.character(1:3)
dat <- data.frame(
rbind(row1, row2),
stringsAsFactors = FALSE
)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With