I have a dataframe with several numeric variables along with factors. I wish to run over the numeric variables and replace the negative values to missing. I couldn't do that.
My alternative idea was to write a function that gets a dataframe and a variable, and does it. It didn't work either.
My code is:
NegativeToMissing = function(df,var)
{
df$var[df$var < 0] = NA
}
Error in $<-.data.frame(`*tmp*`, "var", value = logical(0)) : replacement has 0 rows, data has 40
what am I doing wrong ?
Thank you.
?Extract. I think what you need in there isdf[[var]][ df[[var]] < 0 ] <- NA. When you usedf$var, it expects a column namedvarin the frame, which is not the case. To reference it indirectly, the only method is with[(which should return a single-column frame) or[[(which always returns a vector).