'Convert character into logical

In a survey, I put a question where people can leave any comments. If a participant left any text in the response, I'd recode it as TRUE, but if they did not put anything, I'd recode it as FALSE. (So I am trying to convert a character type variable into a logical type.)

I tried to use:

dataset$variable <- dataset$variable %>% 
  plyr::revalue(c("NA"= FALSE, else = TRUE))

But else = TRUE is not working as I wanted. Does anyone know how I can fix this?

r


Solution 1:[1]

You can use logical operators to get TRUE/FALSE values.

dataset <- data.frame(variable = c('NA', 'A', 'B', 'NA'))
dataset$result <- dataset$variable != "NA"
dataset

#  variable result
#1       NA  FALSE
#2        A   TRUE
#3        B   TRUE
#4       NA  FALSE

If you have real NA values you can use is.na -

dataset <- data.frame(variable = c(NA, 'A', 'B', NA))
dataset$result <- !is.na(dataset$variable)

Solution 2:[2]

I think you want:

%>% ifelse(. == "NA", FALSE, TRUE)

Solution 3:[3]

data$columnName= ifelse(data$columnName== "Something", TRUE, FALSE)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ronak Shah
Solution 2 Brian Montgomery
Solution 3 Martin Gal