Hank Lin
Hank Lin

Reputation: 6479

Create new column of character vectors

I'm trying to combine two columns of type "character" into a new column. That is,

ColA    ColB    ColC
"A"     "1"     c("A", "1")
"B"     "2"     c("B", "2")
"C"     "3"     c("C", "3")

I have tried:

df %>% 
  mutate(ColC = list(ColA, ColB))

and other variants but this doesn't work. Anyone know how to do this?

Upvotes: 1

Views: 362

Answers (3)

rm167
rm167

Reputation: 1247

A simple paste would do the job in this example

df=data.frame(colA=c("A","B","C"), colB=c("1","2","3"))
df$ColC=paste(df$colA, df$colB)
df
  colA colB ColC
1    A    1  A 1
2    B    2  B 2
3    C    3  C 3

Upvotes: 2

Naveen
Naveen

Reputation: 1210

If you do not want to use dplyr df$ColC <- apply(df[,c("ColA", "ColB")], 1, paste, collapse = " ").

Upvotes: 1

akrun
akrun

Reputation: 887118

We can user rowwise

library(tidyverse)
df %>%
    rowwise() %>%
    mutate(ColC = list(c(.)))

Or using pmap

df %>%
  mutate(ColC = pmap(., ~ c(...)))

data

df <- structure(list(ColA = c("A", "B", "C"), ColB = 1:3), 
  class = "data.frame", row.names = c(NA, -3L))

Upvotes: 1

Related Questions