Rilcon42 Rilcon42 - 3 months ago 16
R Question

casting to a data.frame in order to sort columns fails with unimplemented type list

Why does the final cast to a data.frame appear not to work? When I try to sort it I get:

Error in order(temp[, 1], decreasing = T) : unimplemented type 'list' in 'orderVector1'


data<-lapply(1:5,function(i){
lapply(1:5,function(j){
list(i=i,j=j)
})
})

temp<-as.data.frame(data)
temp<-matrix(temp,ncol=2,byrow=T)
head(temp,20)
temp<-data.frame(temp)
class(temp) #####IS A DATA.FRAME
temp<-temp[order(temp[,1],decreasing=T),]

Answer

The columns in the OP's dataset are each list of length 25. We can convert it to a normal data.frame with column vectors.

temp1 <- data.frame(lapply(temp, unlist))

and then do the order

temp1[order(temp1[,1], decreasing = TRUE),]

It is easier to check the structure of the dataset with str

str(temp, list.len = 3)
#'data.frame':   25 obs. of  2 variables:
# $ X1:List of 25
#  ..$ : int 1
#  ..$ : int 1
#  ..$ : int 1
#  .. [list output truncated]
# $ X2:List of 25
#  ..$ : int 1
#  ..$ : int 2
#  ..$ : int 3
#  .. [list output truncated]

Also, we can directly get a data.frame with expand.grid

expand.grid(rep(list(1:5), 2))

Or using CJ from data.table

library(data.table)
CJ(1:5, 1:5)
Comments