schultem
schultem

Reputation: 189

R transition matrix into List of Lists

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!

Upvotes: 1

Views: 462

Answers (1)

Richie Cotton
Richie Cotton

Reputation: 121137

dlply naturally gives you a list (rather than a list of lists). The standard way of calling it would be

(ans_as_list <- dlply(
  Data, 
  .(respondent, task), 
  summarise, 
  res = gettrans(acquisition)
))

This should be suitable for most purposes, but if you really must have a list of lists, use llply (or equivalently, lapply) to restructure.

(ans_as_list_of_lists <- llply(levels(factor(Data$respondent)), function(lvl)
{
  ans_as_list[grepl(paste("^", lvl, sep = ""), names(ans_as_list))]
}))

Upvotes: 2

Related Questions