DF2 <- data.frame(Drug_Intake_Heroin=c('N/A','0','0','N/A','1','1','N/A'),
Drug_Intake_Fentanyl=c('N/A','0','0','N/A','1','1','N/A'),
Drug_Intake_Cocaine =c('N/A','1','0','N/A','0','1','1'),
Drug_Intake_Crack = c('N/A','0','1','1','1','0','N/A'),
not_miss = c('0','4','4','1','4','4','1'))
DF2 <- DF2 %>%
mutate_at(
c("Drug_Intake_Heroin","Drug_Intake_Fentanyl","Drug_Intake_Cocaine","Drug_Intake_Crack"),
funs(case_when(. == "N/A" & DF2$not_miss != "0" ~ "0", TRUE ~ "N/A")))
You can do as follows.
Hope this was helpful! Thanks!
# Option with case_when()
df1 <- DF2 %>%
mutate(across(everything(), ~as.numeric(.))) %>%
mutate(across(contains("Drug"), ~case_when(is.na(.) & not_miss != 0 ~ 0, .)))
#Option with if_else()
df1 <- DF2 %>%
mutate(across(everything(), ~as.numeric(.))) %>%
mutate(across(contains("Drug"), ~if_else(is.na(.) & not_miss != 0, 0, .)))
Why do you say you have a syntax issue? Is the second version of DF2
different from what you expect?
If so, it might be helpful if you could share the "after" table that you expect to calculate from the "before" table you supplied in the first version of DF2
.
Hi. It was suggested that I use the mutate(across( ......))) option. And I think that is correct because I get the correct output
DF3 <- DF2 %>%
mutate(across(
starts_with("Drug_Intake"), \(x) ifelse(x == "N/A" & not_miss != "0", "0", x)))
DF3
# Drug_Intake_Heroin Drug_Intake_Fentanyl Drug_Intake_Cocaine Drug_Intake_Crack not_miss
# 1 N/A N/A N/A N/A 0
# 2 0 0 1 0 4
# 3 0 0 0 1 4
# 4 0 0 0 1 1
# 5 1 1 0 1 4
# 6 1 1 1 0 4
# 7 0 0 1 0 1
Is it not the same as my Option2 above? If that so, I would love for it to be marked as Solution please!
Thanks!
I would suggest @MasterG should credit your post with leading to the use of across()
, but they would be justified in marking their own post as the solution since it is quite different from yours.
I did use the across option, as you suggested, but I did not use the as.numeric and is.na strategy that you employed; it is therefore a distinct solution from yours. You did, however give me the idea with to pursue a different method. Thank you very much.
- MasterG
This topic was automatically closed 7 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.