мой фрейм данных x выглядит так
id
1 42
Мой второй data.frame z:
id amoumt date
1 42 3 2013-09
2 42 8 2013-09
3 42 1 2011-09
Цели:
Я создал этот код:
dates <- as.character(seq(as.Date(min(z$date), max(z$date), by=c("months"))))
Он находит первую и последнюю дату. И тогда у меня есть этот цикл, который не работает:
for (d in dates) {
z %>%
group_by(id) %>%
summarise(amount = sum(amount)) %>%
setNames(c(names(.)[1], paste("in", format(as.Date(d), "%Y-%m"), sep = " "))) %>%
left_join(
.,
x,
by=c("id") )
}
Результат должен выглядеть так:
id 2011-09 2013-09
1 42 0 11
2 42 1 0





Мы можем сделать это с помощью dplyr + tidyr:
library(dplyr)
library(tidyr)
x %>%
inner_join(z) %>%
mutate(row = 1:n()) %>%
group_by(id, date) %>%
filter(which.min(date) || which.max(date)) %>%
summarize(amount = sum(amount),
row = max(row)) %>%
spread(date, amount) %>%
select(-row)
Результат:
# A tibble: 2 x 3
# Groups: id [1]
id `2011-09` `2013-09`
<int> <int> <int>
1 42 NA 11
2 42 1 NA
Данные:
x = structure(list(id = 42L), .Names = "id", class = "data.frame", row.names = "1")
z = structure(list(id = c(42L, 42L, 42L), amount = c(3L, 8L, 1L),
date = structure(c(2L, 2L, 1L), .Label = c("2011-09", "2013-09"
), class = "factor")), .Names = c("id", "amount", "date"), class = "data.frame", row.names = c("1",
"2", "3"))
Решение с использованием dplyr и zoo может быть достигнуто путем преобразования столбца date в тип yearmon. Соедините оба z и x вместе, чтобы выполнять операции для min и max.
library(dplyr)
library(zoo)
z %>% mutate(date = as.yearmon(date, "%Y-%m")) %>%
right_join(x, by = "id") %>%
group_by(id, date) %>%
summarise(amoumt = sum(amoumt)) %>% #Monthly sum
ungroup() %>%
mutate(minDate = min(date), maxDate = max(date))
# # A tibble: 2 x 5
# id date amoumt minDate maxDate
# <int> <S3: yearmon> <int> <S3: yearmon> <S3: yearmon>
# 1 42 Sep 2011 1 Sep 2011 Sep 2013
# 2 42 Sep 2013 11 Sep 2011 Sep 2013
Данные:
z <- read.table(text =
"id amoumt date
1 42 3 2013-09
2 42 8 2013-09
3 42 1 2011-09",
header = TRUE, stringsAsFactors = FALSE)
x <- read.table(text =
"id
1 42",
header = TRUE, stringsAsFactors = FALSE)
xtabs(amoumt~.,merge(x,aggregate(amoumt~.,dat,sum)))?