Reputation: 41
I am trying to apply these four criteria to one dataframe. Is there a way to use it on just one dataframe rather than creating separate dataframes ?
Yellow<- apply(df, 2, function(x) ifelse(x < 45, 'Yellow', ""))
Green <- apply(df, 2, function(x) ifelse(x > 45 & x < 60, 'Green', "" ))
Orange <- apply(df, 2, function(x) ifelse(x > 60 & x < 70, 'Orange', "" ))
Red <- apply(df, 2, function(x) ifelse(x > 45, 'Red', "" ))
Thank you for your help
Upvotes: 1
Views: 45
Reputation: 70623
You can do all the steps in one anonymous function passed to apply
.
apply(df, MARGIN = 2, FUN = function(x) {
x[x < 45] <- "Yellow"
x[x > 45 & x < 60] <- "Green"
x[x > 60 & x < 70] <- "Orange"
x[x > 70] <- "Red"
x
})
Note that you will miss values for 45, 60 and 70 since <
and >
look for values less/greater than x (but not equal). To avoid that, you should use something along the lines of x <= 45
.
Upvotes: 2