【问题标题】:How do I grab the first non-NA column matching a string if a certain column is NA如果某个列是 NA,我如何获取与字符串匹配的第一个非 NA 列
【发布时间】:2019-07-26 23:12:11
【问题描述】:

我没有看到关于这个问题的类似问题(非常具体)。

我有三个人可以选择回答有关患者的问题。这三个人中只有两个人实际用于任何特定的患者(在我的真实数据中,总是选择两个人,但在 10 人中)。

如果最初的两个人不同意,则使用第三人 (3rdOpinion) 并且该意见优先于其他人。

因此,最终结果=第3意见结果,除非最初的两个意见相同(即3rdOpinion为NA),这种情况下最终结果只是最初两个人给出的意见(即第一个非-该患者的该问题的NA值)

所以例如患者 1 的问题 1,Ben 和 Chris 不同意,所以使用 3rdOpinion 作为最终结果。

对于问题 2,患者 2,Adam 和 Chris 均表示“是”,因此最终结果为“是”,未使用第 3 意见。

如何对我的数据进行编码以提供最后两列 Question1_final 和 Question2_final?

#Code to reproduce the data with the desired last two columns:
Patient <- c("1","2","3")
Question1_Adam <- c(NA,"Yes","No")
Question2_Adam <- c(NA,"Yes","No")
Question1_Ben <- c("Yes",NA,"Unlikely")
Question2_Ben <- c("No",NA,"No")
Question1_Chris <- c("Probably","Probably",NA)
Question2_Chris <- c("Unlikely","Yes",NA)
Question1_3rdOpinion <- c("Probably","Yes","No")
Question2_3rdOpinion <- c("No",NA,NA)
Question1_final <- c("Probably","Yes","No")
Question2_final <- c("No","Yes","Unlikely")
df <- data.frame(Patient, Question1_Adam, Question2_Adam, Question1_Ben, Question2_Ben, Question1_Chris, Question2_Chris, Question1_3rdOpinion, Question2_3rdOpinion, Question1_final, Question2_final)

我想我需要这样的东西,但不确定如何编写最后一部分:

df <- transform(df, Q1_final = ifelse(!is.na(Question1_3rdOpinion), Question1_3rdOpinion, *here I would somehow grep the first non-NA question 1 value*))

【问题讨论】:

  • Question2_final 中的最后一个值不应该是“No”,因为 Adam 和 Ben 都注册了“No”?

标签: r if-statement data-manipulation


【解决方案1】:

使用dplyrtidyr 的一种方法是将长格式的数据、separate 问题和人员放入不同的列。对于每个PatientQuestion,检查前两个值是否相同,取那个值还是取第三个值。

library(dplyr)
library(tidyr)

df %>%
  pivot_longer(cols = -Patient, values_drop_na = TRUE) %>%
  separate(name, into = c("Question", "name"), sep = "_") %>%
  group_by(Patient, Question) %>%
  summarise(ans = if (value[1L] == value[2L]) value[1L] else value[3L]) %>%
  mutate(Question = paste0(Question, "_final")) %>%
  pivot_wider(names_from = Question, values_from = ans) %>%
  left_join(df, by = "Patient")

# Patient Question1_final Question2_final Question1_Adam Question2_Adam
#  <fct>   <fct>           <fct>           <fct>          <fct>         
#1 1       Probably        No              NA             NA            
#2 2       Yes             Yes             Yes            Yes           
#3 3       No              No              No             No            
# … with 6 more variables: Question1_Ben <fct>, Question2_Ben <fct>,
#   Question1_Chris <fct>, Question2_Chris <fct>, Question1_3rdOpinion <fct>,
#   Question2_3rdOpinion <fct>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多