小编shr*_*p32的帖子

使用for循环在数据框中创建新列以计算R中的值?

我有两个数据帧df1和df2:

group=c("Group 1", "Group 2", "Group3","Group 1", "Group 2", "Group3")
year=c("2000","2000","2000", "2015", "2015", "2015")
items=c("12", "10", "15", "5", "10", "7")
df1=data.frame(group, year, items)

year=c("2000", "2015")
items=c("37", "22")
df2=data.frame(year,items)
Run Code Online (Sandbox Code Playgroud)

df1包含每年的项目数并按组分隔,df2包含每年的项目总数

我正在尝试创建一个for循环,它将计算每个组类型的项目比例.我正在尝试做类似的事情:

df1$Prop="" #create empty column called Prop in df1
for(i in 1:nrow(df1)){
  df1$Prop[i]=df1$items/df2$items[df2$year==df1$year[i]]
} 
Run Code Online (Sandbox Code Playgroud)

其中循环应该获得每种类型项的比例(通过从df1获取值并除以df2中的总数)并将其列在新列中,但此代码不起作用.

loops r

5
推荐指数
1
解决办法
1351
查看次数

如何使用R中的聚合函数计算数据框中的均值?

我有一个数据框df1:

number=c(4,3,2,3,4,1)
year=c("2000","2000","2000", "2015", "2015", "2015")
items=c(12, 10, 15, 5, 10, 7)
df1=data.frame(number, year, items)
setDT(df1)[, Prop := number/sum(number), by = year]
Run Code Online (Sandbox Code Playgroud)

这样看起来像这样:

  number year items      Prop
1:      4 2000    12 0.4444444
2:      3 2000    10 0.3333333
3:      2 2000    15 0.2222222
4:      3 2015     5 0.3750000
5:      4 2015    10 0.5000000
6:      1 2015     7 0.1250000
Run Code Online (Sandbox Code Playgroud)

我想获取每年项目数的平均值,因此我尝试使用此功能:

mean.df1=aggregate((df1$number*df1$Prop),list(df1$year), mean)
Run Code Online (Sandbox Code Playgroud)

但返回的均值错误值。我希望它返回:

  Group.1        x
1    2000 2.918918
2    2015 2.296296
Run Code Online (Sandbox Code Playgroud)

其中Group.1是年份,x是正确的平均值。

谢谢!

aggregate r

3
推荐指数
1
解决办法
9561
查看次数

标签 统计

r ×2

aggregate ×1

loops ×1