0

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?

monete
  • 19
  • 5
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Note that RStudio is just an IDE. The language you are using is R. – MrFlick Sep 15 '21 at 03:18

4 Answers4

0

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)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

I think you want:

%>% ifelse(. == "NA", FALSE, TRUE)
Brian Montgomery
  • 2,244
  • 5
  • 15
0

A tidyverse approach

library(dplyr)

dataset %>% 
  mutate(variable = if_else(is.na(variable),FALSE,TRUE))
Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32
0
data$columnName= ifelse(data$columnName== "Something", TRUE, FALSE)
Martin Gal
  • 16,640
  • 5
  • 21
  • 39