adam.888
adam.888

Reputation: 7846

R combining the characters of the first two rows of a data frame

I have a dataframe:

dnames <- data.frame(x1= c("a","b"),x2= c("c","d"),x3= c("e", "f"))
dnames

I would like to combine the characters of each of the first two rows of the data frame

dnames1 <- c("ab","cd","ed")
dnames1

I tried:

dnames1 <- paste(dnames[1,],dnames[2,],sep="")
dnames1

But this did not give the correct result. Thank you for your help.

Upvotes: 1

Views: 943

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101239

To keep your code style, you can try the following code

d <- t(dnames)
dnames1 <- paste0(d[,1],d[,2])

such that

> dnames1
[1] "ab" "cd" "ef"

Upvotes: 2

akrun
akrun

Reputation: 887038

For column wise paste, use sapply

sapply(dnames, paste, collapse="")

Or using the OP's method, unlist and paste

paste(unlist(dnames[1,]),unlist(dnames[2,]),sep="")

In tidyverse

library(dplyr)
library(stringr)
dnames %>%
   summarise_all(str_c, collapse='')

Upvotes: 3

Related Questions