gpt4 book ai didi

r - 如何在R中使用dcast计算唯一计数

转载 作者:行者123 更新时间:2023-12-03 16:10:46 26 4
gpt4 key购买 nike

我正在使用dcast转置下表

date               event          user_id
25-07-2020 Create 3455
25-07-2020 Visit 3567
25-07-2020 Visit 3567
25-07-2020 Add 3567
25-07-2020 Add 3678
25-07-2020 Add 3678
25-07-2020 Create 3567
24-07-2020 Edit 3871
我正在使用dcast转置以将我的事件作为列并计数user_id dae_summ <- dcast(ahoy_events, date ~ event, value.var="user_id")但是我没有得到 唯一的用户ID。它多次计数相同的user_id。我该怎么做才能使一个user_id在相同的日期和事件下仅被计数一次。

最佳答案

我们可以使用uniqueN中的data.table

library(data.table)
dcast(setDT(ahoy_events), date ~ event, fun.aggregate = uniqueN)
# date Add Create Edit Visit
#1: 24-07-2020 0 0 1 0
#2: 25-07-2020 2 2 0 1

或使用 pivot_wider中的 tidyrvalues_fn指定为 n_distinct
library(tidyr)
library(dplyr)
ahoy_events %>%
pivot_wider(names_from = event, values_from = user_id,
values_fn = list(user_id = n_distinct), values_fill = list(user_id = 0))
# A tibble: 2 x 5
# date Create Visit Add Edit
# <chr> <int> <int> <int> <int>
#1 25-07-2020 2 1 2 0
#2 24-07-2020 0 0 0 1
数据
ahoy_events <- structure(list(date = c("25-07-2020", "25-07-2020", "25-07-2020", 
"25-07-2020", "25-07-2020", "25-07-2020", "25-07-2020", "24-07-2020"
), event = c("Create", "Visit", "Visit", "Add", "Add", "Add",
"Create", "Edit"), user_id = c(3455L, 3567L, 3567L, 3567L, 3678L,
3678L, 3567L, 3871L)), class = "data.frame", row.names = c(NA,
-8L))

关于r - 如何在R中使用dcast计算唯一计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63092419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com