Mac
Mac

Reputation: 111

Function to change the levels of a factor variable in R

I have a factored variable Clic_1 in a data frame oldata. I want to write a function that will change the value of the factored variables.

head(oldata$CliC_1)
[1] 4 1 5 3 5 5
Levels: 1 2 3 4 5

I tried this function but it is giving NA

try<- function (data,var){
    for (i in 1:nrow(data)){
            if (var[i]== "1"){
                    var[i]<- "Good"
            } else {var[i]<- "Bad"}        
    }
    return (var)
}

Upvotes: 2

Views: 439

Answers (2)

David Arenburg
David Arenburg

Reputation: 92300

Another way would be

factor(oldata$CliC_1 != 1, labels = c('Good', 'Bad'))
# [1] Bad  Good Bad  Bad  Bad  Bad 
# Levels: Good Bad

Upvotes: 2

smci
smci

Reputation: 33970

You don't need a custom function or relevel. Just use ifelse:

factor(ifelse(oldata$CliC_1==1, 'Good', 'Bad'))
# Bad  Good Bad  Bad  Bad  Bad 

Upvotes: 2

Related Questions