Skip to content
Back to formatted view

Raw Message

Message-ID: <CACOCgc=5mREeOSXBydeyu5HkyenAtyG913vciiQC+D7EXQ9n5g@mail.gmail.com>
Date: 2011-12-11T02:06:51Z
From: Xiaobo Gu
Subject: as.factor does not work inside function

Hi,

I am trying to write a function do cast columns of data frame as
factor in a loop, the source is :


as.factor.loop <- function(df, cols){

	if (!is.null(df) && !is.null(cols) && length(cols) > 0)
	{
		for(col in cols)
    {
			df[[col]] <- as.factor(df[[col]])
		}
	}
}


source('D:/ambertuil.r')
x <- 1:5
y <- 2:6
df <- data.frame(x=x, y=y)
as.factor.loop(df, c("x"))

But after the function call, the df data frame does not change,
because

is.factor(df[["x]])
FALSE

But if I call this in R console directlly, it works

for(col in c("x","y")){df[[col]] <- as.factor(df[[col]])}



is.factor(df[["x]])
FALSE


Regards,

Xiaobo Gu