[英]R - combining two columns of a data frame into a vector of the form c(x,y,z…)
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(, ) 请注意,我不想将这些值粘贴在一起,而是将它们保留为第三个向量的元素,形式为c(,)
We can use tidyverse
我们可以使用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
或仅使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.