[英]Keeping only one ID # per month in R
我有一個數據框,其中包含很多ID號及其全年的交易數據。 ID之間有很多重復項,我想擺脫它們,但我想每月擁有一個ID。 如果我使用[!duplicated ...]函數,它在一月份后也會刪除所有ID。 有任何想法嗎?
這是我所擁有的:
Date ID Transaction
1/31/2016 111 10
1/31/2016 111 12
1/31/2016 112 15
2/28/2016 111 50
2/28/2016 112 40
2/28/2016 112 3
這就是我想要的:
Date ID Transaction1 Transaction 2
1/31/2016 111 10 12
1/31/2016 112 15 -
2/28/2016 111 50 -
2/28/2016 112 40 3
謝謝!
我們可以使用點spread
library(tidy verse)
df1 %>%
group_by(Date, ID) %>%
mutate(new = paste0("Transaction", row_number())) %>%
spread(new, Transaction)
# A tibble: 4 x 4
# Groups: Date, ID [4]
# Date ID Transaction1 Transaction2
# <chr> <int> <int> <int>
#1 1/31/2016 111 10 12
#2 1/31/2016 112 15 NA
#3 2/28/2016 111 50 NA
#4 2/28/2016 112 40 3
雖然我知道spread
應該是做到這一點的方法,但我從未能夠使它發揮作用。 我確定Hadley Wickham對此感到不滿意,但是我要解決的問題是將您要散布的Transaction
所有值paste
到帶有summarize
的單個字符串中,然后使用separate
字符串將其拆分為多個列
請注意,如您的示例所示,我們已按日期分組。 如果您實際上想按月份分組,則需要使用lubridate
從Date變量中提取月份值。
library(dplyr)
library(tidyr)
dates %>%
group_by(ID, Date) %>%
summarize(ntrans = length(Transaction),
transactions = paste0(Transaction, collapse = '-')) %>%
separate(transactions,
into = paste0('Transaction', seq_len(max(.$ntrans))),
sep = '-', fill = 'right') %>%
select(-ntrans)
# A tibble: 4 x 4
# Groups: ID [2]
ID Date Transaction1 Transaction2
<int> <fct> <chr> <chr>
1 111 1/31/2016 10 12
2 111 2/28/2016 50 NA
3 112 1/31/2016 15 NA
4 112 2/28/2016 40 3
使用data.table
包的另一種可能性:
data.table::dcast(dat[, Tx := paste0("Tx", rowid(ID)), by=.(Date)],
Date + ID ~ Tx, value.var="Transaction")
輸出:
Date ID Tx1 Tx2
1: 1/31/2016 111 10 12
2: 1/31/2016 112 15 NA
3: 2/28/2016 111 50 NA
4: 2/28/2016 112 40 3
數據:
library(data.table)
dat <- fread("Date ID Transaction
1/31/2016 111 10
1/31/2016 111 12
1/31/2016 112 15
2/28/2016 111 50
2/28/2016 112 40
2/28/2016 112 3")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.