Skip to content
Prev 279963 / 398513 Next

as.factor does not work inside function

Hi Xiaobo,

The problem is that your function is not assigning the results to your
data frame---df is an internatl copy made by the function.  This is
done to prevent calling functions to have unexpected events such as
overwriting objects in the global environment.  Anyway, I think you
can accomplish what you want using lapply():

## your data
df <- data.frame(x=1:5, y=2:6)
## apply the function, as.factor() to all the elements in the first argument
## and save the results in the relevant columns of df
df["x"] <- lapply(df["x"], as.factor)

## check results
is.factor(df[, "x"])

Hope this helps,

Josh
On Sat, Dec 10, 2011 at 6:06 PM, Xiaobo Gu <guxiaobo1982 at gmail.com> wrote: