简体   繁体   English

将两列合并为一个R

[英]Combining two columns into one R

Just a quick question that I am struggling with. 我正在努力的一个简单问题。 I am working in R and have a data frame like so: 我正在R中工作,并具有如下数据框:

>df
V1      V2
Todd    SAFEZONE
Mike    COOLDOWN
Larry   CHICKGUY

And I want to combine the two columns so that I have a resulting data frame with one column where the two factors sharing a column end up one after another: 而且我想将两列合并,以便得到一个带有一列的结果数据帧,其中共享一列的两个因素彼此相继结束:

>df2
V1
Todd
SAFEZONE
Mike
COOLDOWN
Larry
CHICKGUY

What is the most efficient way to do this? 最有效的方法是什么? Sorry if too simple, there are some tricks to text manipulation I need to learn. 抱歉,如果太简单,我需要学习一些文本操作技巧。

Thanks in advance. 提前致谢。

Append (or extract) the two columns so they are side by side, and then flatten the matrix into a single vector. 附加(或提取)两列,使其并排放置,然后将矩阵展平为单个向量。 The flattening goes by row, so this will produce a vector whose elements alternate from each column. 展平按行进行,因此将产生一个向量,其元素从每一列开始交替。 Here's a demo: 这是一个演示:

x1=c('a','b','c')
x2=c('x','y','z')
matrix(rbind(x1,x2),ncol=1)

    [,1]
[1,] "a" 
[2,] "x" 
[3,] "b" 
[4,] "y" 
[5,] "c" 
[6,] "z" 

The resulting column name is easy to change 产生的列名易于更改

> df2 <- do.call(rbind, lapply(1:nrow(df), function(x) t(df[x,])))
> rownames(df2) <- NULL
> df2
##      1         
## [1,] "Todd"    
## [2,] "SAFEZONE"
## [3,] "Mike"    
## [4,] "COOLDOWN"
## [5,] "Larry"   
## [6,] "CHICKGUY"

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM