David Pop
David Pop

Reputation: 3

Using the if statement in a loop to create a class in a data.set in R

I have seen several questions that are similar to mine, but none of those answers is helping me get this code straight.

I want to classify a data set according to a set of a statement using if() statement, making a loop so it can be applied to the whole dataset. Here is my code:

x100 <- c(100,100,85,90,100,75,65,55,95,90)
x20 <- c(100, 95, 60,52,45,36,47,50,90,85)
index <- x100 + x20
code <- data.frame(x100, x20, index)
code$class <-for (i in code){
                 if (x100 < 100 & x20 < 50) { "3"}
                 else if (x100 ==100 & x20 >=50){"2"} 
                 else (x100 == 100 & x20 == 100) "1"
                 }

I just recently started to work with R, sorry if this is a basic question.

Upvotes: 0

Views: 63

Answers (1)

kasterma
kasterma

Reputation: 4469

The code

for(i in code) { ... }

iterates over the columns in your dataframe, not the rows. Use ifelse

with(code, ifelse(x100 < 100 & x20 < 50, '3', ifelse(x100 ==100 & x20 >=50, '2', '1')))

Upvotes: 1

Related Questions