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.

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

ok, and how can i then export all the dataframes to separate csv-files?
@Khell stackoverflow.com/questions/4209512/… and this is what I searched for to find that thread: google.com/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.