我想扩展一个data.frame以包含一个新列,并为该列提供一个在函数内传递的动态分配的名称。 这是一个简化的例子:
passMyName <-function(df, newColTitle) { df2 <-data.frame(df, newColTitle = rep(NA, nrow(df))) return(df2) } randomDF <-data.frame(a=1:3, b=4:6, c=7:9) passMyName(randomDF, myCustomColTitle)这将向data.frame添加一个新列,其变量名由函数“newColTitle”定义。 相反,我想将newColTitle评估为“myCustomColTitle”并将其作为此新列的命名标记传递,以便输出data.fram包含一个名为“myCustomColTitle”的新列。
这可能吗? 也许通过substitute() , deparse() , quote() , eval() , paste()等你可以假设我已经阅读过以下关于这类主题的引子(实际上是几次):
http://adv-r.had.co.nz/Computing-on-the-language.html
但是有些细节并没有完全停留在我身上。
谢谢
I would like to expand a data.frame to include a new column & give this column a dynamically assigned name passed within a function. Here is a simplified example:
passMyName <-function(df, newColTitle) { df2 <-data.frame(df, newColTitle = rep(NA, nrow(df))) return(df2) } randomDF <-data.frame(a=1:3, b=4:6, c=7:9) passMyName(randomDF, myCustomColTitle)This will add a new column to the data.frame with the variable name defined by the function, "newColTitle". Instead, I would like to evaluate newColTitle as "myCustomColTitle" and pass this as the named tag for this new column, such that the output data.fram contains a new column called "myCustomColTitle".
Is this possible? Perhaps via substitute(), deparse(), quote(), eval(), paste() etc. You can assume that I've read the following primer on this type of topic (several times actually):
http://adv-r.had.co.nz/Computing-on-the-language.html
But some details have not quite stuck with me.
Thanks
最满意答案
我认为如果你将新名称作为字符值传递,这将更有意义。 例如
passMyName <-function(df, newColTitle) { df2 <- cbind(df, setNames(list(rep(NA, nrow(df))), newColTitle)) return(df2) } randomDF <-data.frame(a=1:3, b=4:6, c=7:9) passMyName(randomDF , "myCustomColTitle")但如果您真的想使用未评估的表达式,则可以使用
passMyName <-function(df, newColTitle) { newColTitle <- deparse(substitute(newColTitle)) df2 <- cbind(df, setNames(list(rep(NA, nrow(df))), newColTitle)) return(df2) } randomDF <-data.frame(a=1:3, b=4:6, c=7:9) passMyName(randomDF, myCustomColTitle)I think this would make much more sense if you passed the new name in as a character value. For example
passMyName <-function(df, newColTitle) { df2 <- cbind(df, setNames(list(rep(NA, nrow(df))), newColTitle)) return(df2) } randomDF <-data.frame(a=1:3, b=4:6, c=7:9) passMyName(randomDF , "myCustomColTitle")but if you really wanted to use an unevaluated expression, you can use
passMyName <-function(df, newColTitle) { newColTitle <- deparse(substitute(newColTitle)) df2 <- cbind(df, setNames(list(rep(NA, nrow(df))), newColTitle)) return(df2) } randomDF <-data.frame(a=1:3, b=4:6, c=7:9) passMyName(randomDF, myCustomColTitle)更多推荐
发布评论