使用dplyr将多列连接成一列 [英] Concatenate multiple columns into one with dplyr
本文介绍了使用dplyr将多列连接成一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的df结构,但是有很多列和行:
I have a df structured like this, but with a large number of columns and rows:
A B C D
1 4 3 3
并且我想获得由单列组成的df,该列由所有先前元素的串联组成:
and I want to obtain a df with a single column, made by the concatenation of all the previous elements:
A
1
B
4
C
3
D
3
我该怎么办?如果解决方案包括使用dplyr,那就更好了.
How can I do? Better if solutions comprise the use of dplyr.
推荐答案
取消列表
并将其包装在 data.frame
data.frame(col = unlist(df), row.names = NULL)
# col
#1 A
#2 1
#3 B
#4 4
#5 C
#6 3
#7 D
#8 3
或将其设置为 tibble
library(tibble)
tibble(col = unlist(df))
# col
# <fct>
#1 A
#2 1
#3 B
#4 4
#5 C
#6 3
#7 D
#8 3
@Sotos提到的另一个选项是 stack
,但是它需要类字符列
df[] <- lapply(df, as.character)
stack(df)[1]
数据
df <- read.table(text = "A B C D
1 4 3 3")
这篇关于使用dplyr将多列连接成一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文