Assigning factor variable to a new column instead of factor level

I have a data frame like below

df1 <- data.frame(Type=c("A","B","C"),Grade=c(23,22,44))

I need to create a new column "cat" with the condition as below

df1$cat <- ifelse(df1$Grade > 30, df1$Type, "0")

When i print column "cat" i wanted it to return 0,0,C. However it is returning me 0,0,3. Looks like it is returning the factor levels of Type instead of the actual values. Can someone suggest how can i get the desired output?

You can transform the factor to a character.

df1$cat <- ifelse(df1$Grade > 30, as.character(df1$Type), "0")
1 Like

What if i have strings instead of characters in column Type?

as.character() transforms an object to a string, so it will also work with objects that have more than one character

1 Like

In addition to Peddapaan's answar, you could execute the line

options(stringsAsFactors=FALSE)

before you do anything else, that will save you a lot of headache :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.