Alex Rohrer
Alex Rohrer

Reputation: 49

Turn dataframe into list per row creating a vector per row in R

I have the following dataframe df (way bigger in reality):

      A       B       C
1   ORp0    RT1p20  RT2p20  
2   RT3p0   RT4p0   RT5p0   
3   RT3p0   RT4p0   RT5p05

I need to turn this into an object so the structure looks like this

str(df)

List of 3
 $ : chr [1:3] "ORp0"  "RT1p20" "RT2p20"
 $ : chr [1:3] "RT3p0" "RT4p0"  "RT5p0"
 $ : chr [1:3] "RT3p0" "RT4p0"  "RT5p05"

It seems that every row of this list is a vector. How can I achieve this tranformation from a dataframe?

Thank you very much

Upvotes: 1

Views: 38

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 102710

You can try the following options:

  • asplit + unname
> str(Map(unname,asplit(df,1)))
List of 3
 $ 1: chr [1:3(1d)] "ORp0" "RT1p20" "RT2p20"
 $ 2: chr [1:3(1d)] "RT3p0" "RT4p0" "RT5p0"
 $ 3: chr [1:3(1d)] "RT3p0" "RT4p0" "RT5p05"

or a simpler one (by @akrun in the comment)

> str(asplit(unname(df),1))
List of 3
 $ 1: chr [1:3(1d)] "ORp0" "RT1p20" "RT2p20"
  ..- attr(*, "dimnames")=List of 1
  .. ..$ : NULL
 $ 2: chr [1:3(1d)] "RT3p0" "RT4p0" "RT5p0"
  ..- attr(*, "dimnames")=List of 1
  .. ..$ : NULL
 $ 3: chr [1:3(1d)] "RT3p0" "RT4p0" "RT5p05"
  ..- attr(*, "dimnames")=List of 1
  .. ..$ : NULL
 - attr(*, "dim")= int 3
 - attr(*, "dimnames")=List of 1
  ..$ : chr [1:3] "1" "2" "3"
  • unclass + as.data.frame + t
> str(unclass(as.data.frame(t(df))))
List of 3
 $ 1: chr [1:3] "ORp0" "RT1p20" "RT2p20"
 $ 2: chr [1:3] "RT3p0" "RT4p0" "RT5p0"
 $ 3: chr [1:3] "RT3p0" "RT4p0" "RT5p05"
 - attr(*, "row.names")= chr [1:3] "A" "B" "C"

Upvotes: 0

Onyambu
Onyambu

Reputation: 79338

You could use split:

new_list <- split(as.matrix(df), row(df))
new_list
$`1`
[1] "ORp0"   "RT1p20" "RT2p20"

$`2`
[1] "RT3p0" "RT4p0" "RT5p0"

$`3`
[1] "RT3p0"  "RT4p0"  "RT5p05"

str(new_list)
List of 3
 $ 1: chr [1:3] "ORp0" "RT1p20" "RT2p20"
 $ 2: chr [1:3] "RT3p0" "RT4p0" "RT5p0"
 $ 3: chr [1:3] "RT3p0" "RT4p0" "RT5p05"

Upvotes: 1

Duck
Duck

Reputation: 39613

Try this:

#Data
df <- structure(list(A = c("ORp0", "RT3p0", "RT3p0"), B = c("RT1p20", 
"RT4p0", "RT4p0"), C = c("RT2p20", "RT5p0", "RT5p05")), class = "data.frame", row.names = c("1", 
"2", "3"))

Code:

List <- split(df,rownames(df))

Output:

List
$`1`
     A      B      C
1 ORp0 RT1p20 RT2p20

$`2`
      A     B     C
2 RT3p0 RT4p0 RT5p0

$`3`
      A     B      C
3 RT3p0 RT4p0 RT5p05

If you wanna format further you can use next code:

L2 <- lapply(List, function(x) {y <- c(t(x[1,])); return(y)})

That will output:

L2
$`1`
[1] "ORp0"   "RT1p20" "RT2p20"

$`2`
[1] "RT3p0" "RT4p0" "RT5p0"

$`3`
[1] "RT3p0"  "RT4p0"  "RT5p05"

Similar to what you want. Just as observation be careful with rownames and check that they start from 1 to last observation in your dataframe. Sometimes they can be different!

Upvotes: 2

Related Questions