首页 > 解决方案 > 当用户有多个条目时,如何从 R 中的数据框中选择数据?

问题描述

我从我的移动应用程序分析中获得了一些 JSON 数据。数据衡量他们如何使用应用程序,他们喜欢什么活动等。

我正在尝试为我的用户建立“个人资料”,并说明他们在第 0 天和第 7 天的行为如何变化。

对于每个用户,我的分析都会生成一个 ID,以便我识别他们。这些显示在“用户 ID”列中。

有没有办法可以为具有多个条目的用户提取数据。只打开一次应用的用户对我的个人资料分析没有好处。

例如,我只想要用户 1234374648 的数据

用户身份 按下按钮 积分
1234374648 疫苗 5
123437464 疫苗 4
784628178 药物 2
652847484 疫苗 2

标签: r

解决方案


我将增加您的示例数据,因为它没有通过您的约束:

dat <- structure(list(userID = c(1234374648, 123437464, 784628178, 652847484, 1234374648, 123437464, 784628178), Button.pressed = c("Vaccine ", "Vaccine ", "Medicine ", "Vaccine ", "Vaccine ", "Vaccine ", "Medicine "), points = c(5L, 4L, 2L, 2L, 5L, 4L, 2L)), row.names = c(NA, -7L), class = "data.frame")

dat
#       userID Button.pressed points
# 1 1234374648       Vaccine       5
# 2  123437464       Vaccine       4
# 3  784628178      Medicine       2
# 4  652847484       Vaccine       2
# 5 1234374648       Vaccine       5
# 6  123437464       Vaccine       4
# 7  784628178      Medicine       2

(除了第 4 个,所有userID都是重复的652847484,所以我希望下面的输出中有 6 行。)

碱基R

morethan1 <- ave(dat$userID, dat$userID, FUN = length) > 1
morethan1
# [1]  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE
dat[morethan1,]
#       userID Button.pressed points
# 1 1234374648       Vaccine       5
# 2  123437464       Vaccine       4
# 3  784628178      Medicine       2
# 5 1234374648       Vaccine       5
# 6  123437464       Vaccine       4
# 7  784628178      Medicine       2

tidyverse

library(dplyr)
dat %>%
  group_by(userID) %>%
  filter(n() > 1) %>%
  ungroup()
# # A tibble: 6 x 3
#       userID Button.pressed points
#        <dbl> <chr>           <int>
# 1 1234374648 "Vaccine "          5
# 2  123437464 "Vaccine "          4
# 3  784628178 "Medicine "         2
# 4 1234374648 "Vaccine "          5
# 5  123437464 "Vaccine "          4
# 6  784628178 "Medicine "         2

数据表

library(data.table)
as.data.table(dat)[, .SD[.N > 1,], by = .(userID)][]
#        userID Button.pressed points
#         <num>         <char>  <int>
# 1: 1234374648       Vaccine       5
# 2: 1234374648       Vaccine       5
# 3:  123437464       Vaccine       4
# 4:  123437464       Vaccine       4
# 5:  784628178      Medicine       2
# 6:  784628178      Medicine       2

推荐阅读