2017-05-25 92 views
0

我有这样的数据集:子集的数据集

> dput(SampleEvents) 
structure(list(Event = structure(c(10L, 5L, 6L, 11L, 10L, 7L, 
11L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 11L), .Label = c("e10", "e11", 
"e12", "e13", "e2", "e3", "e6", "e8", "e9", "Login", "Logout" 
), class = "factor"), Transaction.ID = structure(c(NA, 1L, NA, 
2L, NA, NA, NA, NA, 3L, NA, NA, NA, NA, NA, NA), .Label = c("t1", 
"t4", "t5"), class = "factor"), User.ID = structure(c(1L, 1L, 
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("kenn1", 
"kenn2"), class = "factor"), Event.Date = structure(c(1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "20/5/2017", class = "factor"), 
    Event.Time = structure(c(12L, 13L, 14L, 15L, 1L, 2L, 3L, 
    4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L), .Label = c("10:01", "10:02", 
    "10:03", "10:04", "10:05", "10:06", "10:07", "10:08", "10:09", 
    "10:10", "10:11", "9:00", "9:30", "9:45", "9:50"), class = "factor")), .Names = c("Event", 
"Transaction.ID", "User.ID", "Event.Date", "Event.Time"), class = "data.frame", row.names = c(NA, 
-15L)) 

enter image description here

我想去掉两个固定值内的所有行下的列“事件”,即,从“行登录”到‘注销’,其中有之间的所有失踪事务ID值‘登录’和‘注销’:

enter image description here

我也想保留数据集的当前顺序。

如何在R中执行此操作?

+0

请不要提供您的数据为图像。对于任何人使用它,他们需要再次输入。相反,请使用文本格式。理想情况下,您可以使用R中的数据并使用'dput'来提供数据结构。您的图像看起来像来自Excel。 _至少_你可以保存为csv并粘贴到你的问题。 – G5W

+0

我对这个网站有点新。让我尝试附加数据集。 –

+0

是的,我想在这里有一个示例并理解逻辑,以便我可以将其应用于我的父数据集中。 –

回答

0

你可以这样做;下面,您所提供的数据工程...

library(dplyr) 

#add variables to mark login-logout blocks and number them 
df <- df %>% mutate(session=cumsum(Event=="Login")-cumsum(Event=="Logout"), 
        block=c(0,cumsum(diff(session)!=0)), 
        block=ifelse(Event=="Logout",block-1,block)) 

#identify blocks to remove 
df2 <- df %>% group_by(block) %>% 
       summarise(Login=first(session)>0, 
         noTrans=all(is.na(Transaction.ID))) %>% 
       filter(Login & noTrans) 

#remove unwanted blocks and delete temporary variables 
df <- df %>% filter(!(block %in% df2$block)) %>% 
      select(-c(session,block)) 

df 
    Event Transaction.ID User.ID Event.Date Event.Time 
1 Login   <NA> kenn1 20/5/2017  9:00 
2  e2    t1 kenn1 20/5/2017  9:30 
3  e3   <NA> kenn1 20/5/2017  9:45 
4 Logout    t4 kenn1 20/5/2017  9:50 
5  e8   <NA> kenn2 20/5/2017  10:04 
6  e9    t5 kenn2 20/5/2017  10:05 
+0

运行第二个代码后,我收到一条警告消息: “Warning warning: In Ops.factor(10L,0):'>'对于因素没有意义” 如果我忽略此操作并运行第三个代码,则I得到一个观测值为零的数据集。 –

+0

检查您是否使用了上述版本 - 我发现了一些错误并对其进行了一些编辑! –

+0

现在没有给出任何警告信息,但数据集似乎没有变化。 –