Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unlist a data frame by rows, not columns

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:

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.

like image 324
Gio Circo Avatar asked Aug 13 '15 13:08

Gio Circo


People also ask

How to unlist a column in a Dataframe in Python?

To such a list with dataframes, we can also apply the unlist command: As you can see, each column of the data matrix is unlisted itself. It is even possible to unlist a string (i.e. a data object of character class ).

Is it possible to unlist a column in a data matrix?

As you can see, each column of the data matrix is unlisted itself. It is even possible to unlist a string (i.e. a data object of character class ). First, let’s modify our list once more: Our new list, my_list_3, consists of three numeric vectors, one data table of the class data.frame, and one character vector.

How to delete rows from a pandas Dataframe?

Pandas provide data analysts a way to delete and filter data frame using dataframe.drop () method. We can use this method to drop such rows that do not satisfy the given conditions. Let’s create a Pandas dataframe. Example 1 : Delete rows based on condition on a column. Example 2 : Delete rows based on multiple conditions on a column.

Is it possible to unlist a string from a list?

It is even possible to unlist a string (i.e. a data object of character class ). First, let’s modify our list once more: Our new list, my_list_3, consists of three numeric vectors, one data table of the class data.frame, and one character vector.


2 Answers

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

 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.

like image 137
akrun Avatar answered Oct 07 '22 13:10

akrun


You can try also 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
like image 23
Chriss Paul Avatar answered Oct 07 '22 12:10

Chriss Paul