按行而不是列取消列表数据框

时间:2021-08-04 14:56:19

A relatively simple question, but the answer seems to have eluded me. Currently, I have a data frame which looks similar to this:

一个相对简单的问题,但答案似乎没有找到我。目前,我有一个类似于这样的数据框:

0   0   0   1   1
0   1   0   1   1
2   1   1   0   3

I'm trying to turn this into a single line of data, by rows. I used the unlist function, and it did what I wanted, but gave them to me by columns. It gave me this:

我试图通过行将其转换为单行数据。我使用了unlist功能,它完成了我想要的功能,但是按列给了我。它给了我这个:

0,0,2,0,1,1,0,0,1,1,1,0,1,1,3

but what I want is this:

但我想要的是这个:

0,0,0,1,1,0,1,0,1,1,2,1,1,0,3

I apologize if this seems like a silly question, but I'm still a novice with R. Any help (or referrals to functions which might help me process this) would be greatly appreciated.

如果这看起来像一个愚蠢的问题我很抱歉,但我仍然是R的新手。任何帮助(或推荐可能帮助我处理这些功能的函数)都将非常感激。

2 个解决方案

#1


15  

We can take the transpose (t) of the dataset and then use c to get a vector output

我们可以采用数据集的转置(t),然后使用c来获得矢量输出

 c(t(df1))
 #[1] 0 0 0 1 1 0 1 0 1 1 2 1 1 0 3

By doing transpose, we convert the 'data.frame' to 'matrix'. In both data.frame or matrix, unlist/c operations happen columnwise. So, transposing swaps the columns for rows and viceversa and we get the expected result.

通过转置,我们将'data.frame'转换为'matrix'。在data.frame或matrix中,unlist / c操作按列发生。因此,转置交换列的行和反之,我们得到预期的结果。

#2


0  

You can try also as.vector():

你也可以尝试as.vector():

x<-matrix(c(0,0,2,0,1,1,0,0,1,1,1,0,1,1,3),3,5)

x
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    1    1
[2,]    0    1    0    1    1
[3,]    2    1    1    0    3

as.vector(t(x))
[1] 0 0 0 1 1 0 1 0 1 1 2 1 1 0 3

#1


15  

We can take the transpose (t) of the dataset and then use c to get a vector output

我们可以采用数据集的转置(t),然后使用c来获得矢量输出

 c(t(df1))
 #[1] 0 0 0 1 1 0 1 0 1 1 2 1 1 0 3

By doing transpose, we convert the 'data.frame' to 'matrix'. In both data.frame or matrix, unlist/c operations happen columnwise. So, transposing swaps the columns for rows and viceversa and we get the expected result.

通过转置,我们将'data.frame'转换为'matrix'。在data.frame或matrix中,unlist / c操作按列发生。因此,转置交换列的行和反之,我们得到预期的结果。

#2


0  

You can try also as.vector():

你也可以尝试as.vector():

x<-matrix(c(0,0,2,0,1,1,0,0,1,1,1,0,1,1,3),3,5)

x
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    1    1
[2,]    0    1    0    1    1
[3,]    2    1    1    0    3

as.vector(t(x))
[1] 0 0 0 1 1 0 1 0 1 1 2 1 1 0 3