【问题标题】:Create new column in data frame using a for loop to calculate value in R?使用for循环在数据框中创建新列以计算R中的值?
【发布时间】:2015-07-13 22:01:00
【问题描述】:

我有两个数据框 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)

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]]
} 

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

【问题讨论】:

  • 只是一个问题:为什么"items 向量中?值实际上是数字,但使用您的语法,它们会转换为因子。

标签: r loops


【解决方案1】:

你真的不需要df2,这是一个使用data.table的简单解决方案,只有df1(我假设items是数字列,如果不是,你需要将其转换为一个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

另一种方法是,如果您已经拥有df2,则可以在两者之间加入并计算Prop(同样,我假设items 是真实数据中的数字)

setkey(setDT(df1), year)[df2, Prop := items/i.items]

一个基本的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

【讨论】:

  • items 是@shrimp32 编写示例的一个因素。
  • 我知道,我说我假设这是一个错误,这实际上是一个数值。
【解决方案2】:

dplyr 相当于大卫的data.table 解决方案

library(dplyr)

df1$items = as.integer(as.vector(df1$items))
df1 %>% group_by(year) %>% mutate(Prop = items / sum(items))

#Source: local data frame [6 x 4]
#Groups: year

#    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

plyr替代

ddply(df1, .(year), mutate, prop = items/sum(items))

lapply替代

do.call(rbind,lapply(split(df1, df1$year), 
        function(x){ x$prop = x$item / sum(x$item); x}))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多