[英]Create new column in R dataframe based on results from 3 other columns
我有一個包含ID和掃描結果的數據框。 如果未在掃描中看到結果,則表示1。 如果看到結果,則為2;如果掃描未完成,則沒有向量。
我希望在數據框的末尾創建一列,以檢查所有3列,如果在3次掃描中的任何一次都沒有看到結果,則返回“ 2”。 如果在掃描中看不到結果,則為“ 1”;如果患者從未以任何三種方式完成掃描,則為“無”。
我已經嘗試在Excel和R中執行此操作。我現在更喜歡使用R,因為我目前正在學習此功能,並希望繼續學習新的用法。
我嘗試使用
library(tidyverse)
USS_reports %>%
mutate((filter(USSfluid=2 | CTfluid=2 | MRIfluid=2))
id USSFluid CTfluid MRIfluid
1 1 1 1
2 1 1
3 1 1 1
4 1 1
5 1 1
6 1 1
7 1
8 1
9 1
10 1 2
11 1 2
乍一看,這是一個不那么簡單的解決方案,但是可以擴展到超過您要檢查的這三列。 我將數據幀gather
為長格式,為所有結果的每個ID制作一個字符串,然后使用case_when
檢查每種可能性:結果為2,結果為1,或者沒有結果。 我喜歡case_when
以避免彼此之間嵌套很多ifelse
。
我還添加了一個測試案例,以解決沒有結果的情況,只是為了確保一切都可以。
library(tidyverse)
df %>%
# test case with no results
bind_rows(tibble(id = 12)) %>%
gather(key = scan, value = result, -id) %>%
group_by(id) %>%
summarise(all_str = paste(result, collapse = ",")) %>%
mutate(overall = case_when(
str_detect(all_str, "2") ~ "2",
str_detect(all_str, "1") ~ "1",
T ~ "no result"
))
#> # A tibble: 12 x 3
#> id all_str overall
#> <dbl> <chr> <chr>
#> 1 1. 1,1,1 1
#> 2 2. 1,1,NA 1
#> 3 3. 1,1,1 1
#> 4 4. 1,1,NA 1
#> 5 5. 1,1,NA 1
#> 6 6. 1,1,NA 1
#> 7 7. 1,NA,NA 1
#> 8 8. 1,NA,NA 1
#> 9 9. 1,NA,NA 1
#> 10 10. 1,2,NA 2
#> 11 11. 1,2,NA 2
#> 12 12. NA,NA,NA no result
由reprex軟件包 (v0.2.0)於2018-04-27創建。
因為要賦予最高優先級,您可以使用apply
來獲取數據幀的每行max
( MARGIN = 1
),但不包括第一個id列( [,-1]
):
USS_reports %>% mutate(summary = apply(USS_reports[,-1], MARGIN = 1,
FUN = function(row)max(row, na.rm = TRUE))) %>%
mutate(summary = ifelse(summary == -Inf, NA, summary))
請注意,當所有cols為NA時,需要使用第二個mutate替換由max返回的-Inf值。 為此,您的df需要為數字。 如果沒有,您首先必須做
USS_reports[] <- lapply(USS_reports, as.numeric)
(順便說一句,如果您想在上面的代碼中測試是否相等,則必須使用==而不是=)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.