Reputation: 109
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
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
Reputation: 1625
Slightly shorter without using $
:
library(dplyr)
tempcat_aq <- airquality %>%
mutate(TempCat = ifelse(Temp > 80, "hot", "cold"))
Upvotes: 1
Reputation: 2301
As mt1022 suggests, a simple base R ifelse
should suffice:
aq$tempcat <- ifelse(aq$Temp > 80, 'hot', 'cold')
Upvotes: 2
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