How do you rename any response/value to 1 and any NA to 0?
Sample Dataframe:
Dataframeexample <- data.frame(Q5 = c("potato", "chips", "chips", "chips,potato","icecream,chips,potato", "icecream,potato", "chips", "NA", "NA"))
My actual dataframe has hundreds of potential combinations, so renaming each potential value individually isn't feasible.
CodePudding user response:
Do you mean like this? I fixed your NA values to be logical rather than characters.
#### Data Fix ####
library(tidyverse) # for mutate later
Dataframeexample <- data.frame(Q5 = c("potato", "chips", "chips",
"chips,potato","icecream,chips,potato",
"icecream,potato",
"chips", NA, NA))
#### Ifelse Statement ####
Dataframeexample %>%
mutate(Q5 = ifelse(is.na(Q5),
0,
1))
Giving you this data:
Q5
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 0
9 0
CodePudding user response:
First of all, if you really have that data, convert "NA"
strings to real NA
.
dat[dat == "NA"] <- NA
Then rename values in the entire data frame at once:
dat[!is.na(dat)] <- 1
dat[is.na(dat)] <- 0
dat
# Q5 Q6
# 1 1 1
# 2 1 1
# 3 1 1
# 4 0 0
# 5 0 0
No need for packages or loops.
Data:
dat <- data.frame(Q5 = c("potato", "chips", "chips,potato", "NA", "NA"),
Q6 = c("potato", "chips", "chips,potato", NA, NA))
CodePudding user response:
Write a function to do the conversions and apply it to the data set's character columns. The function below works even for the true NA
's present in the data.
na_falsetrue <- function(x, value = "NA") {
is.na(x) <- x == value
as.integer(!is.na(x))
}
i_char <- sapply(Dataframeexample, is.character)
Dataframeexample[i_char] <- lapply(Dataframeexample[i_char], na_falsetrue)
Dataframeexample
#> Q5
#> 1 1
#> 2 1
#> 3 1
#> 4 1
#> 5 1
#> 6 1
#> 7 1
#> 8 0
#> 9 0
Created on 2022-10-30 with reprex v2.0.2