我有一个包含数千行的数据框,但下面给出了一个示例:
userid event
1 123 view
2 123 view
3 123 order
4 345 view
5 345 view
6 345 view
7 345 order
8 111 view
9 111 order
10 111 view
11 111 view
12 111 view
13 333 view
14 333 view
15 333 view
输出(数据)
structure(list(userid = c(123, 123, 123, 345, 345, 345, 345,
111, 111, 111, 111, 111, 333, 333, 333), eventaction = structure(c(2L,
2L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("order",
"view"), class = "factor")), .Names = c("userid", "event"
), row.names = c(NA, -15L), class = "data.frame")
我正在做的是提取事件下包含单词“order”的所有用户 ID 行。结果将包含用户 ID 的所有行(不包括用户 ID = 333),因为事件操作不包含订单条目。
第二个任务是统计订单输入之前“查看”出现的次数。我将不胜感激的帮助和指示。
谢谢。
最佳答案
我们可以尝试使用data.table
。将“data.frame”转换为“data.table”(setDT(data)
),按“userid”分组,if
有any
'event' 是 'userid' 中的 'order',返回 Data.table 的子集' (.SD
)
library(data.table)
setDT(data)[,if(any(event=="order")) .SD , by = userid]
或者使用dplyr
,我们在按“userid”分组后过滤
“事件”中的任何
“订单”。
library(dplyr)
data %>%
group_by(userid) %>%
filter(any(event == "order"))
关于r - 根据条件为每个 ID 提取多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39493974/