【问题标题】:Create column for mean of another column, filtered after a dummy variable为另一列的平均值创建列,在虚拟变量后过滤
【发布时间】:2021-11-10 16:56:56
【问题描述】:

我的表看起来(简化)如下:

| countrycode | year | dummy | Value

| "AUS" | 2008 | 1 | -3

| "AUS" | 2009 | 0 | -2

| "BEL" | 2008 | 0 | -5

| "BEL" | 2009 | 1 | -1

| "BEL" | 2010 | 1 | -2

| "BEL" | 2011 | 1 | -1

| "CAN" | 2008 | 0 | -2

| "CAN" | 2009 | 0 | -5

| "CAN" | 2010 | 1 | 2

| "CAN" | 2011 | 0 | -4

我想得到按国家代码分组的值的平均值,如下所示:

| countrycode | year | dummy | Value | Mean

| "AUS" | 2008 | 1 | -3 | -3

| "AUS" | 2009 | 0 | -2 | -3

| "BEL" | 2008 | 0 | -5 | -1,333

| "BEL" | 2009 | 1 | -1 | -1,333

| "BEL" | 2010 | 1 | -2 | -1,333

| "BEL" | 2011 | 1 | -1 | -1,333

| "CAN" | 2008 | 1 | -2 | -0,5

| "CAN" | 2009 | 0 | -5 | -0,5

| "CAN" | 2010 | 1 | 1 | -0,5

| "CAN" | 2011 | 0 | -4 | -0,5

我的问题是如何从在虚拟变量后过滤的另一列中为均值创建一个新列?

【问题讨论】:

标签: r mean dummy-variable


【解决方案1】:
library(dplyr)

your_data_frame %>% 
  filter(dummy == 1) %>%
  group_by(countrycode) %>% 
  summarize(mean = mean(Value, na.rm = TRUE))

【讨论】:

  • 如何添加我只想在 dummy=1 的同一行的值上使用它?
  • 更新了我的答案,使用filter
  • 这样做,我将得到所有值的平均值以及 dummy ==1,但我希望每个国家/地区都有一个唯一值(即它们值的平均值)。感谢您的帮助。
  • 好的,mutate 保留数据维度,总结一下你可以改用summarize/summarise
  • 通过 summarise 我仍然只能得到一个值(所有变量的平均值为 dummy==1)。
【解决方案2】:

也许这就是你要找的。按countrycode 分组后,您可以使用mutate 创建新列。对于每个组,您可以获得Value 的平均值,其中dummy 为1。通过使用mutate,即使dummy 为0,您也会将其添加到组中的所有行。

library(dplyr)

df %>% 
  group_by(countrycode) %>% 
  mutate(mean = mean(Value[dummy == 1]))

输出

   countrycode  year dummy Value  mean
   <chr>       <int> <int> <int> <dbl>
 1 AUS          2008     1    -3 -3   
 2 AUS          2009     0    -2 -3   
 3 BEL          2008     0    -5 -1.33
 4 BEL          2009     1    -1 -1.33
 5 BEL          2010     1    -2 -1.33
 6 BEL          2011     1    -1 -1.33
 7 CAN          2008     1    -2 -0.5 
 8 CAN          2009     0    -5 -0.5 
 9 CAN          2010     1     1 -0.5 
10 CAN          2011     0    -4 -0.5 

数据

df <- structure(list(countrycode = c("AUS", "AUS", "BEL", "BEL", "BEL", 
"BEL", "CAN", "CAN", "CAN", "CAN"), year = c(2008L, 2009L, 2008L, 
2009L, 2010L, 2011L, 2008L, 2009L, 2010L, 2011L), dummy = c(1L, 
0L, 0L, 1L, 1L, 1L, 1L, 0L, 1L, 0L), Value = c(-3L, -2L, -5L, 
-1L, -2L, -1L, -2L, -5L, 1L, -4L)), class = "data.frame", row.names = c(NA, 
-10L))

【讨论】:

    猜你喜欢
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 2016-10-21
    • 1970-01-01
    相关资源
    最近更新 更多