HowYaDoing
HowYaDoing

Reputation: 850

Getting individual lists from an R by object

If you have data like:

x<-1:100
c1<-cut(x,breaks=10 )
result<-by(x,c1,function(x){
                     list(n=length(x),
                          centralTendency=c(mean=mean(x),
                          median=median(x)) ) } )

Is it possible to get a vector of n, and a list of vectors with the central tendency? This is a very simplified form of my problem, which is actually n data points and 280 icc values, so please don't try to calculate the mean and median more efficiently.

Upvotes: 1

Views: 56

Answers (1)

LyzandeR
LyzandeR

Reputation: 37879

Something like this maybe:

n <- unname(sapply(result, function(x) x$n))
#or as per @Frank 's comment
sapply(result,`[[`,"n") 

#n
#[1] 10 10 10 10 10 10 10 10 10 10

And for central tendency

ct <- lapply(result, function(x) x$centralTendancy)
#or as per @Frank 's comment
lapply(result,`[[`,"centralTendency")

#> ct
#$`(0.901,10.9]`
#  mean median 
#   5.5    5.5 
#
#$`(10.9,20.8]`
#  mean median 
#  15.5   15.5 
#
#$`(20.8,30.7]`
#  mean median 
#  25.5   25.5 

Upvotes: 2

Related Questions