My data set is like the following:
Q_B Q1 Q2 Q3 Q4
1 5 4 5 3
2
1 3 4 3 1
2
1 1 1 1 1
What I'm doing is to change Q1 to Q4 to 0 if Q_B==2, I use Q1[Q_B==2]<-0,Q2[Q_B==2]<0
I have to write the same code for Q1 to Q4, is there a easy way to do that? Thanks!
We can just do
df1[df1$Q_B==2,-1] <- 0
df1 <- structure(list(Q_B = c(1L, 2L, 1L, 2L, 1L), Q1 = c(5L, NA, 3L,
NA, 1L), Q2 = c(4L, NA, 4L, NA, 1L), Q3 = c(5L, NA, 3L, NA, 1L
), Q4 = c(3L, NA, 1L, NA, 1L)), .Names = c("Q_B", "Q1", "Q2",
"Q3", "Q4"), class = "data.frame", row.names = c(NA, -5L))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.