![](/img/trans.png)
[英]How to pass multiple list of lists as arguments to mapply function in R
[英]How to mapply a function with multiple variables across multiple lists
我對mapply()有點不了解了,然后打電話。
所以我有兩個清單,像這樣:
ID START END
a1 1/1/2000 1/30/2000
a2 5/4/2000 3/1/2002
a3 5/8/2004 8/7/2005
a4 1/3/2012 5/7/2015
ID START END
b1 5/1/2000 1/30/2020
b2 6/4/2007 3/1/2008
b3 5/8/2014 8/7/2015
b4 1/3/1999 5/7/2019
許多日期相互重疊,這就是我要確定的。 我正在嘗試為第二個列表上的每個條目創建一個列,以說明日期范圍是否重疊...
ID START END b1 b2 b3 b4
a1 1/1/2000 1/30/2000 0 0 0 1
a2 5/4/2000 3/1/2002 1 0 0 1
a3 5/8/2004 8/7/2005 1 0 0 1
a4 1/3/2012 5/7/2015 1 0 1 1
其中0表示不重疊的事件,而1表示重疊。
到目前為止,我的工作一直是在具有多個變量的函數中使用dplyr mutate。 然后我試圖使用mapply將這些變量作為整個列表輸入。
builder <- function(id,start,finish){
resource_const_all <- resource_const %>%
mutate(id = ifelse(start > START & start < END,"1",
ifelse(finish > START & finish < END, "1",
ifelse(start < START & finish > END, "1", "0"))))
}
###if the start date falls in the date range, it returns 1.
###if the end date falls in the date range, it returns 1.
###if the start date is before the date range and the end date is after, it
###returns 1.
###Else the dates don't overlap, returns 0.
builder_output <- mapply(builder,id_list,start_list,end_list))
謝謝你的幫助!
假設在結尾處的注釋中可重復顯示的數據,我們確保START
和END
列為Date
類。 然后如圖所示使用outer
。
請注意, overlap
是通用測試, overlapAB
使其特定於A
和B
不使用任何軟件包。
overlap <- function(start1, end1, start2, end2) {
(start1 >= start2 & start1 <= end2) | (start2 >= start1 & start2 <= end1)
}
overlapAB <- function(idA, idB) {
i <- match(idA, A$ID)
j <- match(idB, B$ID)
overlap(A$START[i], A$END[i], B$START[j], B$END[j])
}
cbind(A, +outer(A$ID, B$ID, overlapAB))
贈送:
ID START END b1 b2 b3 b4
1 a1 2000-01-01 2000-01-30 0 0 0 1
2 a2 2000-05-04 2002-03-01 1 0 0 1
3 a3 2004-05-08 2005-08-07 1 0 0 1
4 a4 2012-01-03 2015-05-07 1 0 1 1
LinesA <- "ID START END
a1 1/1/2000 1/30/2000
a2 5/4/2000 3/1/2002
a3 5/8/2004 8/7/2005
a4 1/3/2012 5/7/2015"
LinesB <- "ID START END
b1 5/1/2000 1/30/2020
b2 6/4/2007 3/1/2008
b3 5/8/2014 8/7/2015
b4 1/3/1999 5/7/2019"
fmt <- "%m/%d/%Y"
A <- read.table(text = LinesA, header = TRUE, as.is = TRUE)
A$START <- as.Date(A$START, fmt)
A$END <- as.Date(A$END, fmt)
B <- read.table(text = LinesB, header = TRUE, as.is = TRUE)
B$START <- as.Date(B$START, fmt)
B$END <- as.Date(B$END, fmt)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.