1

I have a data set with multiple treatments that I imported into R with read.csv. I then manipulated the data (normalized them in various ways) and now have 4 lists of independent, normalized observations for my 4 treatments (listA, listB, listC, listD). These data are not paired and represent independent observations (e.g. sample size in a= 5 and in b =6). I want to combine these lists into a new data file (maybe a .csv or a data frame) from which I can do statistics (ANOVA) and graphing (box plots). The final data set should NOT be a list simply appending all values in one list but should list each value in one column according to which list it came from. E.g. a 5.5 a 5 a 4.8 a 5.5 a 5.3 b 2.2 b 3.1 etc.

I have tried appending but the output only lists the values, not the names of the samples (a - d) next to the values.

my_list <- list(a= listA, b= listB, c= listC, d=listD)
my_list

I get this result:

$a
 [1]  5.5 5 4.8  5.5  5.3  5.5  5.3
$b
 [1]  2.2 3.1 

but I would like to see a table with two columns

a 5.5
a 5
a 4.8
a 5.5
a 5.3
b 2.2
b 3.1
etc.

Trying to do as.data.frame creates this error:

my_df <- as.data.frame(my_list) Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows:

A. Suliman
  • 12,923
  • 5
  • 24
  • 37
  • maybe something similar: https://stackoverflow.com/questions/47254147/how-to-convert-multiple-lists-into-one-dataframe – Ben Jul 17 '19 at 23:16

3 Answers3

6

You can use stack from base R -

my_list <- list(a= c(5.5, 5, 4.8,  5.5,  5.3,  5.5,  5.3),
                b = c(2.2, 3.1))

stack(my_list)

  values ind
1    5.5   a
2    5.0   a
3    4.8   a
4    5.5   a
5    5.3   a
6    5.5   a
7    5.3   a
8    2.2   b
9    3.1   b
Shree
  • 10,835
  • 1
  • 14
  • 36
1

One option:

library(dplyr)

listA <- c(5, 3, 7)
listB <- c(2, 4)

bind_rows(
  enframe(listA, name = NULL) %>% mutate(df = "a"),
  enframe(listB, name = NULL) %>% mutate(df = "b")
)
cardinal40
  • 1,245
  • 1
  • 9
  • 11
0

this would be one way to do it:

x=(unlist(my_list))
df=data.frame(treatment=substring(names(x),1,1), #the substring chops off the numerical part from the names given by unlist
              values=x)
TobiO
  • 1,335
  • 1
  • 9
  • 24