sapply(list(runif (10), runif (10)),
function(x) c(min = min(x), mean = mean(x), max = max(x)))
Why is the above code giving a matrix of 3 rows and 2 columns and not 2 rows and 3 columns ?
Edit (original answer with explanation below) :
We can use ldply
from plyr
as it directly gives us a data.frame
object.
plyr::ldply(list(runif(10),runif(10)),
function(x) c(Min=min(x),Mean=mean(x),Max=max(x)))
# Min Mean Max #No seed
# 1 0.03964594 0.3960042 0.7345305
# 2 0.05233872 0.3811633 0.9713190
Original:
It makes a list with two components:
list(runif(10),runif(10))
From each list, we find the minimum,maximum and mean hence the output. To understand why, try running this alone:
sapply(list(runif (10)), function(x) c(min = min(x), mean = mean(x), max = max(x)))
If you change the simplify
argument, you can get the output you wish(I assume) to have:
sapply(list(runif (10)), function(x) c(min = min(x), mean = mean(x), max = max(x)),
simplify = F)
#[[1]]
# min mean max #No seed
# 0.2482040 0.4845170 0.8294896
NOTE:: You need to set.seed
for reproducibility.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.