gpt4 book ai didi

r - 在 R 中标记唯一值

转载 作者:行者123 更新时间:2023-12-04 11:47:37 25 4
gpt4 key购买 nike

我的数据看起来像:

data <- matrix(c("1","install","2015-10-23 14:07:20.000000",
"2","install","2015-10-23 14:08:20.000000",
"3","install","2015-10-23 14:07:25.000000",
"3","sale","2015-10-23 14:08:20.000000",
"4","install","2015-10-23 14:07:20.000000",
"4","sale","2015-10-23 14:09:20.000000",
"4","sale","2015-10-23 14:11:20.000000"),
ncol=3, byrow=TRUE)
colnames(data) <- c("id","event","time")

我想添加第四列,称为标签,其中我在某些值上相应地标记每一行。在这种情况下:
  • 如果 id 是唯一的,则为“0”标签
  • 如果 id 不是唯一的并且关联了 1 个销售,则为“1”标签
  • 如果 id 不是唯一的并且关联了 2 个销售,则为“2”标签

  • 依此类推,最多为 n 次销售。

    它应该最终看起来像:
    data1 <- matrix(c("1","install","2015-10-23 14:07:20.000000","0",
    "2","install","2015-10-23 14:08:20.000000","0",
    "3","install","2015-10-23 14:07:25.000000","1",
    "3","sale","2015-10-23 14:08:20.000000","1",
    "4","install","2015-10-23 14:07:20.000000","2",
    "4","sale","2015-10-23 14:09:20.000000","2",
    "4","sale","2015-10-23 14:11:20.000000","2"),
    ncol=4, byrow=TRUE)

    我不清楚在 R 中根据条件创建“标签”的最佳方法是什么......也许 dplyr::mutate ?

    最佳答案

    更新以反射(reflect)“等等最多 n 次销售。”-要求。

    dplyr 选项可以是:

    library(dplyr)
    data <- as.data.frame(data)
    data %>%
    group_by(id) %>%
    mutate(label = if(n() == 1) 0 else as.numeric(sum(event == "sale")))

    #Source: local data frame [7 x 4]
    #Groups: id [4]
    #
    # id event time label
    # (fctr) (fctr) (fctr) (dbl)
    #1 1 install 2015-10-23 14:07:20.000000 0
    #2 2 install 2015-10-23 14:08:20.000000 0
    #3 3 install 2015-10-23 14:07:25.000000 1
    #4 3 sale 2015-10-23 14:08:20.000000 1
    #5 4 install 2015-10-23 14:07:20.000000 2
    #6 4 sale 2015-10-23 14:09:20.000000 2
    #7 4 sale 2015-10-23 14:11:20.000000 2

    data.table 等价物将是:
    library(data.table)
    data <- as.data.table(data) # or setDT(data) if it's already a data.frame
    data[, label := if(.N == 1) 0 else as.numeric(sum(event == "sale")), by=id]

    关于r - 在 R 中标记唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33567799/

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