Das ist mein Code im Moment:
z_adjusted <- demographics_cleaned %>%
dplyr::filter(country_live == 'United States of America' | country_live == 'India' | country_live == 'United Kingdom'|country_live == 'Canada') %>% **##filtering only countries of interest**
mutate(z_score_country = case_when(country_live == 'United Sates of America') ~ (money_per_month - US_m) / US_sd, **##attempting to apply the Z score formula based on country**
(country_live == 'India') ~ (money_per_month - IN_m) / IN_sd),
(country_live == 'Canada') ~ (money_per_month - CN_m) / CN_sd),
(country_live == 'United Kingdom') ~ (money_per_month - UK_m) / UK_sd)
) %>%
arrange(desc(z_score_country)) **##arranging to find outliers e.t.c.**
Ich habe die Mittelwerte und Standardabweichungen der Länder außerhalb dieses Codes berechnet und sie den Variablen US_sd, US_m usw. hinzugefügt
Ich möchte case_when verwenden, um die Formel (value - sample mean) / sample SD auszuführen und diese über das Tibble zu mutieren
Dies scheint nicht zu funktionieren. Ich frage mich, ob:
Es gibt einen besseren, eleganteren Weg, dies zu tun
Dieser Weg wird funktionieren, wenn mein Code korrekt ist
Der Fehlercode, den ich bekomme, ist:
Error: unexpected ',' in:
" mutate(z_score_country = case_when(country_live == 'United Sates of America') ~ ((money_per_month - US_m) / US_sd),
(country_live == 'India') ~ (money_per_month - IN_m) / IN_sd),"
> (country_live == 'Canada') ~ (money_per_month - CN_m) / CN_sd),
Error: unexpected ')' in "(country_live == 'Canada') ~ (money_per_month - CN_m) / CN_sd)"
> (country_live == 'United Kingdom') ~ (money_per_month - UK_m) / UK_sd)
Error: unexpected ')' in "(country_live == 'United Kingdom') ~ (money_per_month - UK_m) / UK_sd)"
> ) %>%
Error: unexpected ')' in ")"
> arrange(desc(z_score_country))
Error in desc(z_score_country): object 'z_score_country' not found
Lösung des Problems
Sie können dies einfacher mit einer gruppierten Mutation tun, indem Sie die scale()
Basisfunktion verwenden. Sie können auch verwenden %in%
, um Ihren Filter zu vereinfachen.
Schließlich würde ich nach dem absoluten Wert von arrangieren z_score_country
, um sowohl hohe als auch niedrige Ausreißer zu finden.
library(dplyr)
z_adjusted <- demographics_cleaned %>%
filter(country_live %in% c(
'United States of America',
'India',
'United Kingdom',
'Canada'
)) %>%
group_by(country_live) %>%
mutate(z_score_country = scale(money_per_month)) %>%
ungroup() %>%
arrange(desc(abs(z_score_country)))
Keine Kommentare:
Kommentar veröffentlichen