apply.yearly() 适用于子集,但不适用于 R 中的完整时间序列数据集

apply.yearly() works with subset but not on full time series dataset in R

当我 运行 我的数据集上的以下代码时,我得到如下输出(显示部分):

all_countries_ts[,grepl("Muslims", colnames(all_countries_ts))]

             Senegal Muslims Serbia Muslims Seychelles Muslims
1970-01-01         3693807         200000                170
2000-01-01         8936283         529322                730
2010-01-01        11713126         527598                821
2015-01-01        13621382         471414                844

然而,当我尝试使用函数 apply.yearly 对这些年进行求和时,我只得到了一个 NA 结果:

apply.yearly(all_countries_ts[,grepl("Muslims", colnames(all_countries_ts))], FUN = sum)

1970-01-01   NA
2000-01-01   NA
2010-01-01   NA
2015-01-01   NA

有趣的是,它适用于某些输入,但不适用于其他输入。例如,如果我使用输入 "Agnostics" 而不是 "Muslims",我会得到一个好的结果。没有错误,所以我似乎无法弄清楚这里到底发生了什么。

all_countries_ts 存储为 xts 对象。需要注意的一件事是 apply.yearly() 始终适用于该数据集的一个子集。我写了一个函数,你可以在下面看到它:

sum_by_category <- function(religious_group, dataset) {
apply.yearly(dataset[,grepl(paste(religious_group), colnames(dataset))], FUN = 
sum)
}

country_search <- function(country_name, z){
  z <- foreach(i = 1:length(country_name), .combine = merge.xts) %do%{
    all_countries_ts[,grepl(country_name[i], colnames(all_countries_ts))]
  }
  return(z)}

当我输入以下内容时,它完美运行:

sum_by_category("Muslims", country_search("Senegal"))
               Senegal Muslims
1970-01-01         3693807
2000-01-01         8936283
2010-01-01        11713126
2015-01-01        13621382

我真的不知道发生了什么,因为它适用于某些输入而不是其他输入。在此先感谢您的帮助/见解!

xts::apply.yearly 期望 x 参数可强制转换为 xts 对象。也许您的 data.frame 不是 xts 兼容的数据框。

apply.yearly的帮助说明:

Arguments

x     an time-series object coercible to xts
FUN   an R function

我根据 OP 共享的数据创建了一个示例数据,并将其转换为 xts class。 apply.yearly 同样可以正常工作。

library(xts)

# Convert data.frame to xts class
all_countries_ts <- xts(df[,-1], order.by = df$Date)

#Now one can use `apply.yearly`
apply.yearly(all_countries_ts[,grepl("Muslims", colnames(all_countries_ts))], FUN = sum)

#                [,1]
# 1970-01-01  3893977
# 2000-01-01  9466335
# 2010-01-01 12241545
# 2015-01-01 14093640

已编辑: 对 OP 数据的审查表明它包含许多列的 NA,这导致总和显示为 NA。修复很简单。 OP 需要使用 as:

apply.yearly(all_countries_ts[,grepl("Muslims",colnames(all_countries_ts))],
                FUN = sum, na.rm = TRUE)

#                  [,1]
# 1970-01-01  570772699
# 2000-01-01 1292170756
# 2010-01-01 1571250533
# 2015-01-01 1734531709

数据:

df <- read.table(text = 
" Date             'Senegal Muslims' 'Serbia Muslims' 'Seychelles Muslims' Others
1970-01-01         3693807         200000                170               200
2000-01-01         8936283         529322                730              100
2010-01-01        11713126         527598                821              300
2015-01-01        13621382         471414                844              500",
header = TRUE, stringsAsFactors = FALSE)

#convert Date column to Date format
df$Date <- as.Date(df$Date)