Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

How to know last log before event? R language

I have table like this(input):

user_id    event       timestamp
Rob        business    111111
Rob        business    222222
Mike       progress    111111
Mike       progress    222222
Rob        progress    000001
Mike       business    333333
Mike       progress    444444
Lee        progress    111111
Lee        progress    222222

dput of table:

dput(input)
structure(list(user_id = structure(c(3L, 3L, 2L, 2L, 3L, 2L, 
2L, 1L, 1L), .Label = c("Lee", "Mike", "Rob"), class = "factor"), 
    event = structure(c(1L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 2L), .Label = c("business", 
    "progress"), class = "factor"), timestamp = c(111111, 222222, 
    111111, 222222, 1, 333333, 444444, 111111, 222222)), .Names = c("user_id", 
"event", "timestamp"), row.names = c(NA, -9L), class = "data.frame")

I want to know last progress event before first business event happens (output):

    user_id    event       timestamp
    Mike       progress    222222
    Rob        progress    000001

Thanks for help!!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

We can try with data.table

library(data.table)
setDT(df1)[df1[order(as.numeric(timestamp)), if(any(event == "business")) 
        .I[tail(which(cumsum(event == "business")==0),1)], user_id]$V1]   
#   user_id    event timestamp
#1:     Rob progress    000001
#2:    Mike progress    222222

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...