I have a data frame containing two character columns which I want to combine such that the output will be a vector of characters, like so.
Var1 Var2 Var3
a1 a2 c(a1, a2)
b1 b2 c(b1, b2)
Please note that I do not want to paste these values together but rather leave them as elements of a third vector specifically in the form c(, )
We can use tidyverse
library(tidyverse)
df1 %>%
mutate(Var3 = map2(Var1, Var2, c))
# Var1 Var2 Var3
#1 a1 a2 a1, a2
#2 b1 b2 b1, b2
Or using only base R
df1$Var3 <- do.call(Map, c(f = c, unname(df1)))
str(df1)
#'data.frame': 2 obs. of 3 variables:
# $ Var1: chr "a1" "b1"
# $ Var2: chr "a2" "b2"
#$ Var3:List of 2
# ..$ a1: chr "a1" "a2"
# ..$ b1: chr "b1" "b2"
is.vector(df1$Var3[1])
#[1] TRUE
is.vector(df1$Var3[2])
#[1] TRUE
df1 <- data.frame(Var1 = c("a1","b1"),Var2=c("a2","b2"), stringsAsFactors=FALSE)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.