R 按年度获取总数
我有以下几点意见R 按年度获取总数,r,R,我有以下几点意见 Fund Name Assets_Jan2000 Asset_Feb2000 Asets_Mar2000 x Y 20234 654654 13154 A T 45646 46546544 K L 464654 464 还有更多的专栏——一直到2017年12月 我希望得到每月(如2
Fund Name Assets_Jan2000 Asset_Feb2000 Asets_Mar2000
x Y 20234 654654 13154
A T 45646 46546544
K L 464654 464
还有更多的专栏——一直到2017年12月
我希望得到每月(如2000年1月)以及每年(如2000年、2001年等)的总数
我尝试了以下方法
total <- colSums(assets[, c(3:365)], na.rm = TRUE)
total1 <- as.data.frame(total).
total要按年份获取总计,一种方法是按列名拆分数据,提取年份,然后取所有值的sum
。在base R中,我们可以使用split.default
和sapply
df1 <- df[,c(3:365)]
sapply(split.default(df1, sub(".*?(\\d+$)", "\\1", names(df1))), function(x)
sum(unlist(x), na.rm = TRUE))
我们可以在tidyverse
中使用
library(tidyverse)
gather(df1, Year, Val, matches("^As+et"), na.rm = TRUE) %>%
group_by(Year = readr::parse_number(Year)) %>%
summarise(Val = sum(Val))
或使用base R
aggregate(values ~ cbind(Year = sub("\\D+", "", ind)),
stack(df1[-(1:2)]), FUN = sum, na.rm = TRUE)
或者使用OP帖子中的colSums
结果的aggregate
aggregate(values ~ cbind(Year = sub("\\D+", "", ind)),
stack(colSums(df1[-(1:2)], na.rm = TRUE)), FUN = sum)
数据
df1
aggregate(values ~ cbind(Year = sub("\\D+", "", ind)),
stack(colSums(df1[-(1:2)], na.rm = TRUE)), FUN = sum)
df1 <- structure(list(und = c("x", "A", "K"), Name = c("Y", "T", "L"
), Assets_Jan2000 = c(20234L, 45646L, 464654L), Asset_Feb2000 = c(654654L,
46546544L, NA), Asets_Mar2000 = c(13154L, NA, 464L)),
class = "data.frame", row.names = c(NA,
-3L))