mercredi 30 décembre 2020

Combination of for-loop and ifelse in R

I'm trying to decide between "Yes" and "No" in R, if a specific (and variable) value is exceeded. For each value tested a new column with the different decisions should be created.

Here is a manually created example:

Test.data <- data.frame(c(10, 20, 30, 40, 50, 60, 70, 80, 90, 100))
colnames(Test.data) <- c("Test")

Test.data$Test1 <- ifelse(Test.data$Test > 10, "Yes", "No")
Test.data$Test2 <- ifelse(Test.data$Test > 20, "Yes", "No")
Test.data$Test3 <- ifelse(Test.data$Test > 30, "Yes", "No")

Test.data

This simple example gives the following output:

   Test Test1 Test2 Test3
1    10    No    No    No
2    20   Yes    No    No
3    30   Yes   Yes    No
4    40   Yes   Yes   Yes
5    50   Yes   Yes   Yes
6    60   Yes   Yes   Yes
7    70   Yes   Yes   Yes
8    80   Yes   Yes   Yes
9    90   Yes   Yes   Yes
10  100   Yes   Yes   Yes

Is there a way to do this with a for-loop? I already tried different stuff like the following code, but it seems to be nonsense, since it doesn't create new columns and so on:

n = c(seq(from=10, to=100, by=10))

for(i in n) {
ifelse(Test.data$Test > i, "Yes", "No")
}

Thanks everyone!

Aucun commentaire:

Enregistrer un commentaire