我正在尝试将R中数据帧的多个列组合成一个向量。最简单的方法是什么?
我的数据框架如下:
X1 X2 X3 X4
----------------------
Paul John Cissy Paul
Rob Rob Rob Amanda
所需的输出是
X1
---
Paul
Rob
John
Rob
Cissy
Rob
Paul
Amanda
答案 0 :(得分:3)
使用unlist
:
df <- data.frame(X1 = c("Paul","Rob"), X2 = c("John", "Rob"))
v <- unlist(df)
给出:
> str(v)
Factor w/ 3 levels "Paul","Rob","John": 1 2 3 2
- attr(*, "names")= chr [1:4] "X11" "X12" "X21" "X22"
您可以使用unname(v)
删除属性名称。
答案 1 :(得分:3)
使用stack
df5[] <- lapply(df5[], as.character) #make sure your columns are not factors
setNames(stack(df5)[1], 'X1')
# X1
#1 Paul
#2 Rob
#3 John
#4 Rob
#5 Cissy
#6 Rob
#7 Paul
#8 Amanda
答案 2 :(得分:2)
我们可以尝试
data.frame(X1 = c(as.matrix(df)))
# X1
#1 Paul
#2 Rob
#3 John
#4 Rob
#5 Cissy
#6 Rob
#7 Paul
#8 Amanda