mak
September 7, 2021, 3:08pm
1
Good aftenoon ,
I want to add colums in dataframe with mutate function , in order I classify the risque (Risque 0 is saine),Risque"1and2"is subclinique and Risque(3,4,5)is clinique, give me errors , Thank you
sick%>%mutate(cas = ifelse(RISQUE=="1","2","subclinique",
ifelse (RISQUE=="3","4","5" ,"clinique",
ifelse( RISQUE=="0","saine"))))
Try this
sick <- data.frame(
RISQUE = c("0","1","2","3","4","5","6")
)
print(sick)
#> RISQUE
#> 1 0
#> 2 1
#> 3 2
#> 4 3
#> 5 4
#> 6 5
#> 7 6
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
sick %>%
mutate(cas =
ifelse(RISQUE %in% c("1", "2"), "subclinique",
ifelse (RISQUE %in% c("3", "4", "5") , "clinique",
ifelse(RISQUE == "0", "saine","unknown"))
))
#> RISQUE cas
#> 1 0 saine
#> 2 1 subclinique
#> 3 2 subclinique
#> 4 3 clinique
#> 5 4 clinique
#> 6 5 clinique
#> 7 6 unknown
Created on 2021-09-07 by the reprex package (v2.0.0)
1 Like
For multiple conditions is better to use case_when()
instead of nested ifelse()
library(dplyr)
# Sample data in a copy/paste friendly format, replace this with your own data frame
sick <- data.frame(
RISQUE = c("0","1","2","3","4","5","6")
)
# Relevant code
sick %>%
mutate(cas = case_when(
RISQUE %in% c("1", "2") ~ "subclinique",
RISQUE %in% c("3", "4", "5") ~ "clinique",
RISQUE == "0" ~ "saine",
TRUE ~ "unknown"
))
#> RISQUE cas
#> 1 0 saine
#> 2 1 subclinique
#> 3 2 subclinique
#> 4 3 clinique
#> 5 4 clinique
#> 6 5 clinique
#> 7 6 unknown
Created on 2021-09-07 by the reprex package (v2.0.1)
1 Like
mak
September 7, 2021, 7:13pm
4
That's it , thank you so much for your help
mak
September 7, 2021, 7:14pm
5
Thank you so much for your help
system
Closed
September 28, 2021, 7:15pm
6
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.