[英]delete rows where amount or rows per group greater than value of grouped dataframe in r
[英]Delete grouped rows from a dataframe
我有一個48503行的數據幀。 數據框有多個用戶ID,可以進行多次模擬或只進行一次,唯一的方法是查看用戶所做模擬之間的時差。 如果這個時間差超過20秒,那么我們假設那個人然后在不同的會話中進行模擬。
我想為每個用戶創建一個包含模擬會話編號的新列
(ID) (Simulation Number) (Simulation-time-difference) (Session)
A 1 0:00:00.00 1
A 2 0:00:08.22 1
A 3 0:00:20.67 2
A 4 0:00:05.38 2
B 5 0:00:00.00 1
B 6 0:00:03.32 1
B 7 0:00:28.45 2
這是在提取秒后使用ave
和cumsum
一種方法:
# extract the seconds
df$seconds <- as.numeric(gsub("^0:00:([0-9]{2}\\.[0-9]{2})", "\\1", df$V3))
# calculate the session number
df$session <- ave((df$seconds > 20), df$V1, FUN=cumsum) + 1
這產生了所需的輸出。
df
V1 V2 V3 seconds session
1 A 1 0:00:00.00 0.00 1
2 A 2 0:00:08.22 8.22 1
3 A 3 0:00:20.67 20.67 2
4 A 4 0:00:05.38 5.38 2
5 B 5 0:00:00.00 0.00 1
6 B 6 0:00:03.32 1 3.32 1
7 B 7 0:00:28.45 2 28.45 2
數據
df <- read.table(text=" A 1 0:00:00.00
A 2 0:00:08.22
A 3 0:00:20.67
A 4 0:00:05.38
B 5 0:00:00.00
B 6 0:00:03.32
B 7 0:00:28.45", as.is=TRUE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.