简体   繁体   English

R-将数据帧的两列合并为c(x,y,z…)形式的向量

[英]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

data 数据

df1 <- data.frame(Var1 = c("a1","b1"),Var2=c("a2","b2"), stringsAsFactors=FALSE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将具有x,y和z的列表转换为数据帧,其中x,y和z在R中的长度不相等 - Convert a list with x, y and z to data frame where x, y and z are of unequal lengths in R 将向量转换为 R 中具有两列的数据框 - Transformation of a vector to a data frame with two columns in R 通过组合两列的信息在R中构造数据帧 - construct a data frame in R from combining information of two columns 检索数据框中两列中最重复的(x,y)值 - Retrieve the most repeated (x, y) values in two columns in a data frame 在数据框中合并向量列和列表列 - combining vector and list columns within a data frame R代码相当于:“如果x是data.frame y的一部分”,则返回z“ - R code equivalent to: “if x is part of the data.frame y”, then return z" 合并数据框中的两列,并在R中的现有数据框中创建新列 - Combining two columns in a data frame and creating a new column in an existing data frame in R 将c(“x”,“y”,“z”)之类的矢量转换为函数(x,y,z){} - Convert vector like c(“x”,“y”,“z”) to function(x , y, z){} 将两个数据帧组合成R中的两列 - Combining two data frames into two columns in R (将数据重新转换为R中的交叉引用表)在两个分类变量(X和Y)上标注的变量(Z) - (Recasting data as cross reference table in R) Extracting variable (Z) dimensioned on two categorical variables (X & Y)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM