簡體   English   中英

添加作為時間序列數據幀中重復數字的二進制指示符的列的最有效方法是什么?

[英]What is the most efficient way to add a column that is a binary indicator of a recurring number in time series dataframe?

我有一個類似於此示例數據框的數據框:

example <- data.frame(id = c("1","1","1", "1", "2", "2", "2"),
                      amount = c(2300, 1765, 2300, 1500, 35, 180, 180),
                      date = c("2010-11-01", "2010-11-02", "2010-11-03", "2010-11-04", "2010-11-01", "2010-11-02", "2010-11-03"))

我想添加一列,該列將有一個 1 來指示金額是否為經常性金額。 如果金額在同一 ID 內重復,則只能將經常性金額視為經常性金額。 所以它看起來像這樣:

desiredResult <- data.frame(id = c("1","1","1", "1", "2", "2", "2"),
                      amount = c(2300, 1765, 2300, 1500, 2300, 180, 180),
                      date = c("2010-11-01", "2010-11-02", "2010-11-03", "2010-11-04", "2010-11-01", "2010-11-02", "2010-11-03"),
                      probableRecurringAmount = c(1,0,1,0,0,1,1)) 

數據集非常大,我很難想出一個有效的解決方案。 我正在考慮根據這些其他列的組合向列添加鍵,但我只想有一個二進制標志。

你可以這樣做:

library(dplyr)    
example %>%
  group_by(id, amount) %>%
  mutate(probableRecurringAmount  = ifelse(n() > 1, 1, 0))

# A tibble: 7 x 4
# Groups:   id, amount [5]
# id      amount date       probableRecurringAmount
#<fct>  <dbl> <fct>                        <dbl>
#1 1       2300 2010-11-01                       1
#2 1       1765 2010-11-02                       0
#3 1       2300 2010-11-03                       1
#4 1       1500 2010-11-04                       0
#5 2         35 2010-11-01                       0
#6 2        180 2010-11-02                       1
#7 2        180 2010-11-03                       1

您可以使用duplicated來查找重復的行,然后與原始數據連接以標記原始數據和重復數據。

library(tidyverse)
example <- data.frame(id = c("1","1","1", "1", "2", "2", "2"),
                      amount = c(2300, 1765, 2300, 1500, 35, 180, 180),
                      date = c("2010-11-01", "2010-11-02", "2010-11-03", "2010-11-04", "2010-11-01", "2010-11-02", "2010-11-03"))

# Find duplicated rows
dups = example %>% 
  select(id, amount) %>% 
  mutate(recurring=as.numeric(duplicated(.))) %>% 
  filter(recurring==1)

# Flag both the original and duplicated rows as recurring
example %>% left_join(dups, ) %>% 
  replace_na(list(recurring=0))
#> Joining, by = c("id", "amount")
#>   id amount       date recurring
#> 1  1   2300 2010-11-01         1
#> 2  1   1765 2010-11-02         0
#> 3  1   2300 2010-11-03         1
#> 4  1   1500 2010-11-04         0
#> 5  2     35 2010-11-01         0
#> 6  2    180 2010-11-02         1
#> 7  2    180 2010-11-03         1

reprex 包(v0.3.0) 於 2020 年 1 月 14 日創建

我們可以使用從base R duplicated

example$recurring <-  +(duplicated(example[c('id', 'amount')])|
         duplicated(example[c('id', 'amount')], fromLast = TRUE))
example$recurring
#[1] 1 0 1 0 0 1 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM