3

So I have multiple dataframes, that follow the pattern below:

df1<-data.frame(id=c("1","2","1","2"),choice=c(1,1,1,2))
df2<-data.frame(id=c(...),choice=c(...))
df1
  id choice
1  1      1
2  2      1
3  1      1
4  2      2

now I want to know, how often each individual chooses the different choices:

df1_cast<-dcast(df1,choice~id,value.var = "choice",fill = 0,fun.aggregate = length)
df1_cast
  choice 1 2
1      1 2 1
2      2 0 1

As I have multiple dataframes, I tried looping it with a for loop:

experiments<-list(df1,df2,...)
for (i in 1:length(experiments)){
  dcast(experiments[i],choice~id,value.var="choice",fill=0,fun.aggregate=length)

}

Sadly, the dataframes are saved as lists inside the list and the dcast function cannot find the value.var.

M--
  • 25,431
  • 8
  • 61
  • 93
Khell
  • 33
  • 2

1 Answers1

2

You can use lapply:

df1<-data.frame(id=c("1","2","1","2"),choice=c(1,1,1,2))
df2<-data.frame(id=c("1","2","1","2"),choice=c(2,2,2,1))
experiments<-list(df1,df2)

library(reshape2)

lapply(experiments, function(dfx) 
                     dcast(dfx,choice~id,value.var = "choice", 
                               fill = 0,fun.aggregate = length))

#> [[1]]
#>   choice 1 2
#> 1      1 2 1
#> 2      2 0 1
#> 
#> [[2]]
#>   choice 1 2
#> 1      1 0 1
#> 2      2 2 1
M--
  • 25,431
  • 8
  • 61
  • 93
  • ok, and how can i then export all the dataframes to separate csv-files? – Khell Jul 13 '19 at 22:20
  • @Khell https://stackoverflow.com/questions/4209512/write-list-of-data-frames-to-separate-csv-files-with-lapply and this is what I searched for to find that thread: https://www.google.com/search?rlz=1C1GCEA_enUS821US821&ei=dlkqXYLtMc6PtAbD77fQBg&q=export+list+of+dataframes+to+csv+in+r&oq=export+list+of+dataframes+to+csv+in+r&gs_l=psy-ab.3..33i22i29i30l6.4992.5551..5623...0.0..0.105.395.3j1......0....1..gws-wiz.......0i71.Uuqz7-2Wu_0 – M-- Jul 13 '19 at 22:22