【发布时间】:2014-04-15 17:25:42
【问题描述】:
目标是让函数调用的最后一个参数为要绑定到原始数据框的新列提供名称。
参考this 和this 上一个问题,并以第一个问题的最小工作示例为基础。
GroupId <- c(1,1,1,1,2,2,2,3,3)
IndId <- c(1,1,2,2,3,4,4,5,5)
IndGroupProperty <- c(1,2,1,2,3,3,4,5,6)
PropertyType <- c(1,2,1,2,2,2,1,2,2)
df <- data.frame(GroupId, IndId, IndGroupProperty, PropertyType)
df
ValidGroupC <- c(1,1,1,1,0,0,0,0,0)
df <- data.frame(df, ValidGroupC)
df
library(dplyr)
grouptest <- function(object, group, ind, type, new){
groupvar <- deparse(substitute(group))
indvar <- deparse(substitute(ind))
typevar <- deparse(substitute(type))
eval(substitute(
tmp <- object[, c(groupvar, indvar, typevar)] %.%
group_by(group, ind) %.%
mutate(type1 = any(type == 1)) %.%
group_by(group, add = FALSE) %.%
mutate(tmp2 = all(type1) * 1) %.%
select(-type1)
))
new <- tmp[, 4] # this is the relevant part
tmp <- cbind(object, new) # this is the relevant part
}
df <- grouptest(df, GroupId, IndId, PropertyType, ValidGroup)
df
所以大部分代码已经是引用问题的产物。这个问题的相关部分在最后,我将我对tmp 所做的计算的第 4 列放入一个新对象中,该对象的名称应取自函数调用中的new 参数,然后我将其绑定到原始数据框。
我的问题:为什么最后一列 df 没有命名为 ValidGroup ?
我不明白有什么问题 - new 应该替换为 ValidGroup,但不是吗?
我尝试将这两行放在eval() 中,结果为Error in cbind(df, ValidGroup) : object 'ValidGroup' not found。
我尝试在两条线周围加上另一个eval(substitute()),同样的错误。
我已经尝试了许多其他变体来放置线条,使用经过解析的newvar,将tmp 命名为new,。 . .
【问题讨论】:
标签: r function arguments naming-conventions