我有一些缺少值的数据(即NA值),简化格式如下(末尾输入代码):
#> id x country
#> 1 1 2.0 USA
#> 2 2 4.0 USA
#> 3 3 3.5 JPN
#> 4 4 NA JPN
对于每个国家,我都想
x
,以及可用值的计数
十
(即不是NA),所以我使用
group_by
,它对
mean
以下内容:
df <- df %>% group_by(country) %>%
mutate(mean_x = mean(x, na.rm = TRUE),
#count_x = count(x))
)
df
#> # A tibble: 4 x 4
#> # Groups: country [2]
#> id x country mean_x
#> <dbl> <dbl> <fct> <dbl>
#> 1 1 2 USA 3
#> 2 2 4 USA 3
#> 3 3 3.5 JPN 3.5
#> 4 4 NA JPN 3.5
但是当我试图添加
count()
,我有个错误
library(tidyverse)
df <- data.frame(id = c(1, 2, 3, 4),
x = c(2, 4, 3.5, NA),
country = c("USA", "USA", "JPN", "JPN")
)
df
df <- df %>% group_by(country) %>%
mutate(mean_x = mean(x, na.rm = TRUE),
count_x = count(x))
)
df
#> Error in UseMethod("summarise_") : no applicable method for 'summarise_' applied to an
#> object of class "c('double', 'numeric')"
我想要的结果是:
#> id x country mean_x count
#> <dbl> <dbl> <fct> <dbl>
#> 1 1 2 USA 3 2
#> 2 2 4 USA 3 2
#> 3 3 3.5 JPN 3.5 1
#> 4 4 NA JPN 3.5 1
可复制代码如下:
library(tidyverse)
df <- data.frame(id = c(1, 2, 3, 4),
x = c(2, 4, 3.5, NA),
country = c("USA", "USA", "JPN", "JPN")
)
df
df <- df %>% group_by(country) %>%
mutate(mean_x = mean(x, na.rm = TRUE),
count_x = count(x))
)
df