Thursday, 5 September 2013

If statement in R: Vector of tests and actions

If statement in R: Vector of tests and actions

Some sample data:
ID S1Qual S2Qual S3Qual S1 S2 S3
1 1 0 1 7 8 7
2 1 1 1 6 6 8
3 0 1 1 7 8 8
...
S1Qual, S2Qual, and S3Qual denote the quality of S1PS, S2PS, and S3PS,
respectively. If [n, S1Qual] == 1, I want to keep [n, S1PS]; if [n,S1Qual]
== 0, I want to set [n,S1PS] == NA.
I have the following code:
n <- 1
while (n <= number.of.rows) {
if (data$S1Qual[n] == 0) {data$S1[n] <- NA}
if (data$S2Qual[n] == 0) {data$S2[n] <- NA}
if (data$S3Qual[n] == 0) {data$S3[n] <- NA}
n <- n+1
}
This does what I wanted, but I was hoping there was a more
efficient/concise way (in the real dataframe, there are many more than
three of these S/SQual pairs). Searching around has lead me to ifelse()
and apply(), both of which seem close but not quite right for what I want,
unless I'm thinking about it wrong.
Any ideas?

No comments:

Post a Comment