I have the following problem:
For each row in a data frame I want to copy a value from one column to another depending on a value in third column.
I tried to do it with a combined for loop and if function:
data$retribution <- NULL
data$special_prevention <- NULL
data$general_prevention <- NULL
for (i in 1:length(data$subject_nr)) { #loop to check every row
if (data$condition_rating[i] == 1) {
data$retribution[i] <- data$SZ08_01[i]
data$special_prevention[i] <- data$SZ06_01[i]
data$general_prevention[i] <- data$SZ07_01[i]
} else if (data$condition_rating[i] == 2) {
data$retribution[i] <- data$SZ07_01[i]
data$special_prevention[i] <- data$SZ08_01[i]
data$general_prevention[i] <- data$SZ06_01[i]
} else if (data$condition_rating[i] == 3) {
data$retribution[i] <- data$SZ06_01[i]
data$special_prevention[i] <- data$SZ07_01[i]
data$general_prevention[i] <- data$SZ08_01[i]
} else {
data$retribution[i] <- "missing_condition"
data$special_prevention[i] <- "missing_condition"
data$general_prevention[i] <- "missing_condition"
}
}
This seems to work (no error message), but looking at my data there must be something wrong.
For example row 1 has condition_rating == 3. This means, that for this row data$retribution should have the same value as data$SZ06_01.
But it doesn't. Is there anyone that can see the mistake I made?
Aucun commentaire:
Enregistrer un commentaire