[R] objects of class "matrix" and mode "list"?
Stephen Tucker
brown_emu at yahoo.com
Fri Mar 23 20:03:30 CET 2007
Hello everyone,
I cannot seem to find information about objects of class "matrix" and mode
"list", and how to handle them (apart from flattening the list). I get this
type of object from using sapply(). Sorry for the long example, but the code
below illustrates how I get this type of object. Is anyone aware of
documentation regarding this object?
Thanks very much,
Stephen
===== begin example ====
# I am just making up a fake data set
df <- data.frame(Day=rep(1:3,each=24),Hour=rep(1:24,times=3),
Name1=rnorm(24*3),Name2=rnorm(24*3))
# define a function to get a set of descriptive statistics
tmp <- function(x) {
# this function will accept a data frame
# and return a 1-row data frame of
# max value, colname of max, min value, and colname of min
return(data.frame(maxval=max(apply(x,2,max)),
maxloc=names(x)[which.max(apply(x,2,max))],
minval=min(apply(x,2,min)),
minloc=names(x)[which.min(apply(x,2,min))]))
}
# Now applying function to data:
# (1) split the data table by Day with split()
# (2) apply the tmp function defined above to each data frame from (1)
# using lapply()
# (3) transpose the final matrix and convert it to a data frame
# with mixed characters and numbers
# using as.data.frame(), lapply(), and type.convert()
> final <- as.data.frame(lapply(as.data.frame(t(sapply(split(df[,-c(1:2)],
+
f=df$Day),tmp))),
+ type.convert,as.is=TRUE))
Error in type.convert(x, na.strings, as.is, dec) :
the first argument must be of mode character
I thought sapply() would give me a data frame or matrix, which I would
transpose into a character matrix, to which I can apply type.convert()
and get the same matrix as what I would get from these two lines (Fold
function taken from Gabor's post on R-help a few years ago):
Fold <- function(f, x, L) for(e in L) x <- f(x, e)
final2 <- Fold(rbind,vector(),lapply(split(df[,-c(1:2)],f=day),tmp))
> print(c(class(final2),mode(final2)))
[1] "data.frame" "list"
====================================================
However, by my original method, sapply() gives me a matrix with mode, "list"
intermediate1 <- sapply(split(df[,-c(1:2)],f=df$Day),tmp)
> print(c(class(intermediate1),mode(intermediate1)))
[1] "matrix" "list"
Transposing, still a matrix with mode list, not character:
intermediate2 <- t(sapply(split(df[,-c(1:2)],f=day),tmp))
> print(c(class(intermediate2),mode(intermediate2)))
[1] "matrix" "list"
Unclassing gives me the same thing...
> print(c(class(unclass(intermediate2)),mode(unclass(intermediate2))))
[1] "matrix" "list"
____________________________________________________________________________________
Be a PS3 game guru.
More information about the R-help
mailing list