r - 当用户有多个条目时,如何从 R 中的数据框中选择数据?
问题描述
我从我的移动应用程序分析中获得了一些 JSON 数据。数据衡量他们如何使用应用程序,他们喜欢什么活动等。
我正在尝试为我的用户建立“个人资料”,并说明他们在第 0 天和第 7 天的行为如何变化。
对于每个用户,我的分析都会生成一个 ID,以便我识别他们。这些显示在“用户 ID”列中。
有没有办法可以为具有多个条目的用户提取数据。只打开一次应用的用户对我的个人资料分析没有好处。
例如,我只想要用户 1234374648 的数据
用户身份 | 按下按钮 | 积分 |
---|---|---|
1234374648 | 疫苗 | 5 |
123437464 | 疫苗 | 4 |
784628178 | 药物 | 2 |
652847484 | 疫苗 | 2 |
解决方案
我将增加您的示例数据,因为它没有通过您的约束:
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
推荐阅读
- sql - 查询以仅提取相关的列或具有特定 where 条件的数据
- python - QT Opencv人脸检测在Python中不起作用?
- javascript - antialias=false 在 MacOS 上使用 Safari 阻碍 readPixels
- java - Android:无论发生什么变化,xml都不会更新运行时
- nlp - 是否有公认的策略来获得与 NLP 中的人或地点相关的形容词(或对人或地点的一般印象)?
- c# - 有没有办法简化重复的吸气剂?
- r - 为什么 html 表不给我 p 值并添加 -9 值?表格1
- javascript - TypeError:未定义不是对象(评估“this.state.imagesID”)
- java - java - 如何在java中使用并行数组打印扫描仪元素?
- algorithm - 向量的最小子集,使得它们和的每个分量都大于某个阈值