问题
I am using ave()
function to get minimum of observations with the same factor level:
minX = ave(x, list(factorA), FUN=min)
I wonder what would be an alternative using some of the functions from apply
family? In particular, what would be an alternative to put proper result back in the dataframe? For example, lets have a small data.frame
:
d = data.frame(
x = c(2,3,3,6,5,7,8,8,9,9),
factorA = c('a','a','a','a','a','b','b','b','b','b')
)
# function ave automatically enables proper filling of subsets
# defined by the factorA:
d$minX = ave(d$x, list(d$factorA), FUN=min)
# tapply was my first bet, but it does not produce right result:
d$minX2 = tapply(d$x, list(d$factorA), min)
# combination of split and sapply gives back the same wrong
# result as tapply:
d$minX3 = sapply(split(d$x, d$factorA), min)
And here are results and the differences:
d
# x factorA minX minX2 minX3
# 1 2 a 2 2 2
# 2 3 a 2 7 7
# 3 3 a 2 2 2
# 4 6 a 2 7 7
# 5 5 a 2 2 2
# 6 7 b 7 7 7
# 7 8 b 7 2 2
# 8 8 b 7 7 7
# 9 9 b 7 2 2
# 10 9 b 7 7 7
Only ave()
returns correct minimum of x
given factorA
.
Thanks!
来源:https://stackoverflow.com/questions/32403769/in-r-what-would-be-an-alternative-to-ave-using-some-function-from-apply-fami