I would like to convert a vector into a transitions matrix first (which I managed). As a second step I would like apply the resulting function to a dataset where different respondents did different tasks.
As a result I would like to get a List which is nested on Respondent and Task.
Here is an example data frame:
Data <- data.frame(
respondent = c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2),
task = c(1,1,1,1,1,2,2,2,2,2,1,1,1,1,1,2,2,2,2,2),
acquisition = sample(1:5, replace = TRUE)
)
and here my result vector and function that takes the acquisition vector and generates a transition matrix:
result <- matrix(data = 0, nrow = 5, ncol = 5)
gettrans <- function(invec){
for (i in 1:length(invec)-1){
result[invec[i],invec[i+1]] <- result[invec[i], invec[i+1]] + 1
}
return(result)
}
Now, I get a flattened result with
with(Data,aggregate(acquisition,by=list(respondent=respondent,task=task),gettrans))
However what I would like would look something like:
$respondent
[1]$task[1]
result
$respondent
[1]$task[2]
result
...
I played around with dlply but could not get that to work …
Any suggestions appreciated!
dlplynaturally gives you a list (rather than a list of lists). The standard way of calling it would beThis should be suitable for most purposes, but if you really must have a list of lists, use
llply(or equivalently,lapply) to restructure.