我有两个数据帧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中的总数)并将其列在新列中,但此代码不起作用.
你真的不需要df2,这是一个仅使用data.tableand only 的简单解决方案df1(我假设items是数字列,如果不是,你需要将其转换为 1 setDT(df1)[, items := as.numeric(as.character(items))])
library(data.table)
setDT(df1)[, Prop := items/sum(items), by = year]
df1
# group year items Prop
# 1: Group 1 2000 12 0.3243243
# 2: Group 2 2000 10 0.2702703
# 3: Group3 2000 15 0.4054054
# 4: Group 1 2015 5 0.2272727
# 5: Group 2 2015 10 0.4545455
# 6: Group3 2015 7 0.3181818
Run Code Online (Sandbox Code Playgroud)
另一种方法是,如果您已经有了df2,您可以在两者之间加入并Prop在这样做时进行计算(同样,我假设items在实际数据中是数字)
setkey(setDT(df1), year)[df2, Prop := items/i.items]
Run Code Online (Sandbox Code Playgroud)
基础 R 替代方案
with(df1, ave(items, year, FUN = function(x) x/sum(x)))
## [1] 0.3243243 0.2702703 0.4054054 0.2272727 0.4545455 0.3181818
Run Code Online (Sandbox Code Playgroud)