Consider this simple example
> tibble(id = c(1,2,3,4),
+ score1 = c('good', 'bad', 'bad', 'ugly'),
+ score2 = c('good', 'ugly', 'good', 'bad'))
# A tibble: 4 x 3
id score1 score2
<dbl> <chr> <chr>
1 1 good good
2 2 bad ugly
3 3 bad good
4 4 ugly bad
Essentially, my scoring variable states that good
> bad
> ugly
. Is there a way in R (maybe using ordered factors?) so that
mutate(mycomp = score1 >= score2)
will return the correct answer? That is TRUE
, TRUE
, FALSE
, FALSE
?
Thanks!
Hi Olaf:
If you want to solve this by mutate() the best option, I think, is:
%>% mutate(mycomp = score1 == score2)
If you are trying to make an equal or higer (lower) test, the most elegant solution I can picture it's recode your factors to numeric values.
Regards,
Tona
Yes, have you tried?
library(tidyverse)
df <- tibble(id = c(1,2,3,4),
score1 = c('good', 'bad', 'bad', 'ugly'),
score2 = c('good', 'ugly', 'good', 'bad'))
df %>%
mutate_at(vars(starts_with("score")),
factor,
levels = c("ugly", "bad", "good"),
ordered = TRUE) %>%
mutate(mycomp = score1 >= score2)
#> # A tibble: 4 x 4
#> id score1 score2 mycomp
#> <dbl> <ord> <ord> <lgl>
#> 1 1 good good TRUE
#> 2 2 bad ugly TRUE
#> 3 3 bad good FALSE
#> 4 4 ugly bad FALSE
Created on 2020-04-20 by the reprex package (v0.3.0.9001)
1 Like
system
Closed
4
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.