'Loop to create new variable based on answers to other variables
I would like to create a new variable based on the answers to three other variables (A,B and C) in my data set. Basically my variables have three modalities : "often", "sometime" and "never". I would like to have a new variable in which each individuals has a grade ranging from 0 to 3. For each variable (A,B and C), if he answers "often", he gets 1 point otherwise, he gets 0.
My data set looks like this with "often" coded with 2 ; "sometimes" coded with 1 and "never" coded with 0.
A <- c(2,1,1,NA, 0,2)
B <- c(2,2,0,1,2,NA)
C <- c(2,1,NA,2,1,0)
data <- data.frame(A,B,C)
I know I could use case_when but it is a rather unwieldy solution. I was thinking of a loop but I never used loops in R. Can you help me with this loop?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|