Arun
Arun

Reputation: 625

Converting factors to numeric in R

I have 100s of columns in my database as factors. They actually contains numbers, but R considers them as factors. For my project requirement, I want to convert them to numeric.

I can do that in bulk using sapply / for loop. However i am not sure how to check that variable contains numbers? I cannot just check is.factor(var_name) as the data base also contains character variables which are considered as factors.

is there some other way to execute the below check:

if (is.numeric(var_name)) {
    convert the variable to numeric
}

I am looking for something similar to "stringasfactors= FALSE" which is used for retaining character variable as a character variable instead of converting to factors.

Any help/pointer would be really helpful.

Upvotes: 1

Views: 220

Answers (1)

akrun
akrun

Reputation: 887118

One way would be to use type.convert after converting all the columns to character

df1[] <- lapply(df1, function(x) type.convert(as.character(x)))

Now, the non-numeric character columns will be converted to factor class. We can reconvert those columns back to character

df1[] <- lapply(df1, function(x) if(is.factor(x)) as.character(x) else x)

Upvotes: 1

Related Questions