Mike JJ
Mike JJ

Reputation: 87

How to concatenate different values in different columns in a new column?

suppose I have something like this:

dat <- data.frame(ID = c("A", "B", "C"), 
                  value = c(1, 2, 3))

I would like to add an extra column in which I have a value like this: [A,1]

It would be a column in which each single values are the concatenation of "[" + A (value in the first column) + "," + B (value in the second column) + "]". How can I do it? I tried with paste but I am doing something wrong.

Upvotes: 1

Views: 87

Answers (2)

user8571351
user8571351

Reputation:

Here's an approach that will work consistently with endless numbers of columns:

dat$conc <- paste0("[",apply(dat,1,paste,collapse=","),"]")

Using your example:

dat <- data.frame(ID = c("A", "B", "C"), value = c(1, 2, 3))
dat$conc <- paste0("[",apply(dat,1,paste,collapse=","),"]")

Gives:

  ID value  conc
1  A     1 [A,1]
2  B     2 [B,2]
3  C     3 [C,3]

Or if we have a dataframe with more columns:

dat <- data.frame(ID = c("A", "B", "C"), value = c(1, 2, 3), value2 = c(4, 5, 6))
dat$conc <- paste0("[",apply(dat,1,paste,collapse=","),"]")

Gives:

  ID value value2    conc
1  A     1      4 [A,1,4]
2  B     2      5 [B,2,5]
3  C     3      6 [C,3,6]

Upvotes: 2

mfidino
mfidino

Reputation: 3055

Assuming this is your data

dat <- data.frame(ID = c("A", "B", "C"), value = c(1, 2, 3))

This would work

dat$concat <- paste0("[", dat$ID, ", ", dat$value, "]")

  ID value concat
1  A     1 [A, 1]
2  B     2 [B, 2]
3  C     3 [C, 3]

Or if you did not want the space after the comma:

dat$concat <- paste0("[", dat$ID, ",", dat$value, "]")

Upvotes: 2

Related Questions