What's wrong with my R function for computing conditional means? -
i've begun teaching myself r, , decided try create function calculates mean of variable in data frame conditional on variable in same data frame equalling value. here code:
conditional.mean <- function( df, tv, cvar, cval ) { col1 <- df$tv col2 <- df$svar subdf <- data.frame( col1, col2 ) tv.cond <- subdf[ which(col2==cval), 1 ] x <- mean( tv.cond ) return( x ) }
df
data frame, tv
target variable conditional mean computed, cvar
variable used in condition, , cval
value checked cvar
.
when run code above, function outputs na
, gives following warning: "in mean.default(tv.cond) : argument not numeric or logical: returning na
." don't understand why saying this, since tv.cond should vector of values of target variable cvar
= cval
.
thanks help!
Comments
Post a Comment