R - 按组计算插值平均值的误差
R - Error computing interpolated mean by group
我正在尝试按组计算多个变量的插值中位数。
我的数据框如下所示:
# A tibble: 6 x 8
id eu_image eu_insurance eurobonds free_movement_welfare eu_cn_solidarity country_code country_party_mass
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl+lbl> <chr>
1 CAWI200000100 4 4 4 3 3 2 germany_7
2 CAWI300000784 2 2 1 1 1 3 italy_9
3 CAWI100000787 3 3 2 2 3 1 france_13
4 CAWI500000081 3 2 2 1 3 5 spain_2
5 CATI500000067 4 3 2 2 6 5 spain_3
6 CAWI100000398 2 4 4 2 5 1 france_2
当我运行下面的代码通过分组变量country_party_mass计算插值平均值时:
party_median <- newdata %>%
group_by(country_party_mass) %>%
dplyr::summarise_at(c( "eu_image",
"eu_cn_solidarity",
"eurobonds",
"free_movement_welfare",
"eu_insurance"),
funs(interp.median(., na.rm=TRUE))) %>%
as.data.frame()
我收到以下错误:
Error in summarise_impl(.data, dots) :
Column eu_cn_solidarity
must be length 1 (a summary value), not 0
我已经检查了以前关于类似问题的问题,但找不到可行的解决方案。
基于 A. Suliman 的评论:
您可以添加一个 ifelse
函数来检查是否所有条目都是 NA
:
party_median <- newdata %>%
group_by(country_party_mass) %>%
dplyr::summarise_at(vars(c("eu_image",
"eu_cn_solidarity",
"eurobonds",
"free_movement_welfare",
"eu_insurance")),
~ifelse(all(is.na(.)), NA_real_, interp.median(., na.rm=TRUE)))
请注意,funs
函数现在已被软弃用(从 dplyr 0.8.0.1 开始),因此我改用“~”符号。我还使用 vars
函数来 select 变量。
我正在尝试按组计算多个变量的插值中位数。 我的数据框如下所示:
# A tibble: 6 x 8
id eu_image eu_insurance eurobonds free_movement_welfare eu_cn_solidarity country_code country_party_mass
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl+lbl> <chr>
1 CAWI200000100 4 4 4 3 3 2 germany_7
2 CAWI300000784 2 2 1 1 1 3 italy_9
3 CAWI100000787 3 3 2 2 3 1 france_13
4 CAWI500000081 3 2 2 1 3 5 spain_2
5 CATI500000067 4 3 2 2 6 5 spain_3
6 CAWI100000398 2 4 4 2 5 1 france_2
当我运行下面的代码通过分组变量country_party_mass计算插值平均值时:
party_median <- newdata %>%
group_by(country_party_mass) %>%
dplyr::summarise_at(c( "eu_image",
"eu_cn_solidarity",
"eurobonds",
"free_movement_welfare",
"eu_insurance"),
funs(interp.median(., na.rm=TRUE))) %>%
as.data.frame()
我收到以下错误:
Error in summarise_impl(.data, dots) : Column
eu_cn_solidarity
must be length 1 (a summary value), not 0
我已经检查了以前关于类似问题的问题,但找不到可行的解决方案。
基于 A. Suliman 的评论:
您可以添加一个 ifelse
函数来检查是否所有条目都是 NA
:
party_median <- newdata %>%
group_by(country_party_mass) %>%
dplyr::summarise_at(vars(c("eu_image",
"eu_cn_solidarity",
"eurobonds",
"free_movement_welfare",
"eu_insurance")),
~ifelse(all(is.na(.)), NA_real_, interp.median(., na.rm=TRUE)))
请注意,funs
函数现在已被软弃用(从 dplyr 0.8.0.1 开始),因此我改用“~”符号。我还使用 vars
函数来 select 变量。