philuix
philuix

Reputation: 109

Add column with condition either "hot" or "cold" in relation to temperature in R

I want to create a new column with a condition "if Temperatur > 80 show hot in rows else show cold in the rows"

this is my code:

tempcat_aq <- aq %>% group_by(aq$Temp) %>% mutate(TempCat = if(any(aq$Temp > 80) "hot" else "cold"))

I'm using the airquality dataframe build-in in R and the dplyr library.

Thanks for helping me out.

Upvotes: 1

Views: 93

Answers (4)

TarJae
TarJae

Reputation: 78927

You could use ifelse in your dplyr workflow with the suggestions of Ronak and SteveM

library(dplyr)

tempcat_aq <- aq %>% 
  group_by(Temp) %>% 
  mutate(TempCat = ifelse(Temp > 80, "hot","cold")))

Upvotes: 2

mgrund
mgrund

Reputation: 1625

Slightly shorter without using $:

library(dplyr)

tempcat_aq <- airquality %>% 
              mutate(TempCat = ifelse(Temp > 80, "hot", "cold"))

Upvotes: 1

SteveM
SteveM

Reputation: 2301

As mt1022 suggests, a simple base R ifelse should suffice:

aq$tempcat <- ifelse(aq$Temp > 80, 'hot', 'cold')

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388982

Don't use $ while using dplyr pipes, it is not needed and it breaks the grouping.

library(dplyr)
aq <- airquality

tempcat_aq <- aq %>% 
               group_by(Temp) %>% 
               mutate(TempCat = if(any(Temp > 80)) "hot" else "cold")

Upvotes: 2

Related Questions