Reputation: 329
I have a 4-scale questionnaire data, with questions which have NAs by design. For example, if the answer to question 1 was no (coded by 0), then the rest of the questions aren't applicable to the participants and will be coded as NA. However, these NAs are different from people who simply chose to ignore the question. So I am trying to replace NAs to Q2 & 3 with 0 only if the answer to Q1 was 0, otherwise leave NAs as it. I have made a data frame to further explain my situation:
Q1 <- c(0,0,1,2,0,4)
Q2 <- c(NA,NA,2,1,NA,NA)
Q3 <- c(NA,NA,2,1,NA,4)
data <- cbind(Q1,Q2,Q3)
Q1 Q2 Q3
1 0 NA NA
2 0 NA NA
3 1 2 2
4 2 1 1
5 0 NA NA
6 4 NA 4
Intended output:
Q1 Q2 Q3
1 0 0 0
2 0 0 0
3 1 2 2
4 2 1 1
5 0 0 0
6 4 NA 4
In the intended output, if Q1 was 0, then the NAs in Q2 and 3 were changed to 0. With participant 6, the NA was left as is.
I am teaching myself R and have really been struggling with this.
I've tried the if
,mutate_if
, if_else
, and case_when
functions all to no avail. Somebody help please me.
Here's an example of one of the code's I've tried which gave me an error.
data %>%
ifelse (Q1 == 0) {
mutate(Q2 = coalesce(Q2,0))
}
Upvotes: 1
Views: 719
Reputation: 101317
A data.table
option
> setDT(data)[Q1 == 0, `:=`(Q2 = 0, Q3 = 0)][]
Q1 Q2 Q3
1: 0 0 0
2: 0 0 0
3: 1 2 2
4: 2 1 1
5: 0 0 0
6: 4 NA 4
Upvotes: 1
Reputation: 887088
In base R
we can create a logical index for i
, select the columns in j
and do the assignment
data[!data$Q1, -1] <- 0
data
# Q1 Q2 Q3
#1 0 0 0
#2 0 0 0
#3 1 2 2
#4 2 1 1
#5 0 0 0
#6 4 NA 4
data <- data.frame(Q1,Q2,Q3)
Upvotes: 1
Reputation: 21937
This should work:
library(dplyr)
data %>%
as.data.frame() %>%
mutate(across(c(Q2,Q3), ~case_when(Q1 == 0 ~ 0, TRUE ~ .)))
# Q1 Q2 Q3
# 1 0 0 0
# 2 0 0 0
# 3 1 2 2
# 4 2 1 1
# 5 0 0 0
# 6 4 NA 4
Your code failed because ifelse()
wants a vector as input and provides a vector as output. You could also use ifelse()
instead of case_when()
if you wanted.
library(dplyr)
data %>%
as.data.frame() %>%
mutate(across(c(Q2,Q3), ~ifelse(Q1 == 0, 0, .)))
Upvotes: 2