[英]R: Calculating the number of occurrences within a specific time period in the past for each unique individual in a dataset in R
[英]data manipulation in R: how many time did an individual spend within each period?
在R
,我有三個時間點
時間<-c(7,1,4)
並假設將時間段分為三個間隔:(0,3],(3,5],(5,8]
breaks <- c(3, 5, 8)
timeSpent
的每個觀察結果都有一行,而每個期間都有一列。 它給出了每個觀察在每個時期花費的時間:
timeSpent <- outer(X=time, Y=breaks, FUN=pmin)
timeSpent <- cbind(timeSpent[, 1],
sapply(X=1:(length(breaks) - 1), FUN=function(ii)
timeSpent[, ii + 1] - timeSpent[, ii]))
> timeSpent
[,1] [,2] [,3]
[1,] 3 2 2
[2,] 1 0 0
[3,] 3 1 0
例如,觀察值1在時間間隔1中花費了3天,在時間間隔2中花費了2天,在時間間隔3中花費了2天。對於觀察值2,它在時間間隔1中僅花費了1天,而在其余時間間隔中則什么也沒有。
您是否有更優雅的方式來獲取timeSpent
?
這有幫助嗎?
我們將零列cbind
到timeSpent
矩陣,這樣我們可以得到在第一個觀察窗中花費的初始時間,並將diff
函數apply
行...
res <- t( apply( cbind( 0 , timeSpent ) , 1 , diff ) )
[,1] [,2] [,3]
[1,] 3 2 2
[2,] 1 0 0
[3,] 3 1 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.