[英]nested loop and multiple if statement R
我有一個數據集a
,如下所示
Dictionary ActMin ActMax
3145 5 10
32441 10 19
3245 25 32
416356 37 46
4H22 82 130
%ABC 1 27
我有另一個數據集b
,如下所示
ID Test Obs Year
1 3145-MN 11 1994
2 3145-NY 17 1992
1 416356-FL 57 1995
1 32441-MN 13 1995
2 3145-MN 8 1993
2 3245-NY 27 1983
3 3245-FL 45 2003
2 3145-MN 6 2001
3 %ABC-NY 33 1996
4 4H22-TX 97 1984
我想做的是產生這樣的output
Id Test Obs Results Year Description
1 3145-MN 11 High 1994 Tested 3145 High on 1994, 4163 High on 1995,
2 3145-NY 17 High 1992 Tested 3145 High on 1992
1 416356-FL 57 High 1995
1 32441-MN 13 Normal 1995
2 3145-MN 8 Normal 1993
2 3245-NY 27 Normal 1983
3 3245-FL 45 High 2003 Tested 3245 High on 2003
2 3145-MN 6 Normal 2001
3 %ABC-NY 33 High 1996
4 4H22-TX 27 Normal 1984
該第一數據集a
是存儲唯一的測試號的字典3145
, 3244
等以及它們的Minimum
和Maximum
的值
第二個數據集b
是實際測試結果數據集,用於存儲實際觀察到的結果。 將b
特定測試的觀察值與數據集a
的最小值和最大值進行a
。 如果所觀察到的值b
大於在實際的最小值和最大值大於a
隨后導致柱應該被更新為high
,否則Normal
。 description
列應提供每個ID列出的測試摘要(每個ID的1個摘要)。
需要有關此復雜循環以及if語句和結果聚合的幫助。
有點復雜,但結果應該與你問的相似。 我設法在基礎R中獲取result
列,但是對於Description
我必須使用data.table
。
b$result<-c("Normal","High")[(b$Obs > a$ActMax[match(substr(b$Test,1,4),as.character(a$Dictionary))])+1]
require(data.table)
setDT(b)
b[,Description:=gsub("(, )+$","",c(paste(ifelse(result=="High",paste("Tested",substring(Test,1,4),result,"on",Year),""),collapse=", "),rep("",.N-1))),by=ID]
通過使用dplyr,可以發現代碼更具可讀性:
library(dplyr)
df_result <-
b %>%
## EDIT mutate( Dictionary = as.numeric(substring(Test,1,4)) ) %>%
mutate( Dictionary = as.numeric( gsub("[A-Z,-]+", "", Test )) ) %>%
inner_join(a, by = "Dictionary") %>%
mutate( Results = ifelse( Obs > pmax(ActMin, ActMax), yes = "High", no = "Normal" ))
df_description <-
df_result %>%
filter( Results == "High") %>%
group_by(ID) %>%
summarise(
Results = Results[1],
Dictionary = min(Dictionary),
Description = paste("Tested", Dictionary, "on", Year,collapse = ","))
df_final <-
df_result %>%
left_join( df_description, by = c("ID","Dictionary", "Results")) %>%
select(ID, Test, Obs, Results, Year, Description)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.