Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:创建年度/国内平均值_R - Fatal编程技术网

R:创建年度/国内平均值

R:创建年度/国内平均值,r,R,我试图创建一个平均变量,用于计算一个国家内不同年份观测值的平均国家水平值 我的数据如下所示: party_id year country position 101 1984 be 2.75 101 1988 be 2.75 101 1992 be 3.33 101 1996 be 3.67 102 1984 be 5.80 102 1988 be

我试图创建一个平均变量,用于计算一个国家内不同年份观测值的平均国家水平值

我的数据如下所示:

party_id year country position
    101 1984      be     2.75
    101 1988      be     2.75
    101 1992      be     3.33
    101 1996      be     3.67
    102 1984      be     5.80
    102 1988      be     5.80

例如,我想要一个平均变量,它将有1984年比利时所有政党的平均立场,等等

使用
aggregate
您可以按国家和年份获得平均值

aggregate(position ~ country + year, data = df,  mean)

  country year position
1      be 1984    4.275
2      be 1988    4.275
3      be 1992    3.330
4      be 1996    3.670
另一种可能更具可读性的方法是使用
dplyr

library(dplyr)
df %>%
  group_by(country, year) %>%
  summarise(mean(position))
编辑-向数据添加变量的操作请求,您可以使用
mutate

df %>%
  group_by(country, year) %>%
  mutate(mean(position))
@bounchball建议的基本解决方案

merge(x = df,y = aggregate(position~year+country, data = df, FUN = mean), 
      by = c('year','country'))

使用
aggregate
可以按国家和年份获得平均值

aggregate(position ~ country + year, data = df,  mean)

  country year position
1      be 1984    4.275
2      be 1988    4.275
3      be 1992    3.330
4      be 1996    3.670
另一种可能更具可读性的方法是使用
dplyr

library(dplyr)
df %>%
  group_by(country, year) %>%
  summarise(mean(position))
编辑-向数据添加变量的操作请求,您可以使用
mutate

df %>%
  group_by(country, year) %>%
  mutate(mean(position))
@bounchball建议的基本解决方案

merge(x = df,y = aggregate(position~year+country, data = df, FUN = mean), 
      by = c('year','country'))

谢谢,然后我如何用平均值创建一个新变量,这样行的数量足够大,观测值匹配?在base中,你可以:
合并(x=df,y=aggregate(pos~year+country,data=df,FUN=mean),by.x=c('year','country'),by.y=c('year','country'))
@bounchyball谢谢,实际上可以进一步简化为
by=c('year','country')
,因为名称是相同的。谢谢,然后我如何用平均值创建一个新变量,以便行数足够大,观察值匹配?在base中,您可以:
merge(x=df,y=aggregate(pos~year+country,data=df,FUN=mean),by.x=c('year','country'),by.y=c('year','country'))
@bouncyball谢谢,实际上可以进一步简化为
by=c('year','country')
,因为名称相同。