as.formula does not like equivalence '=' (object not found)

匆匆过客 提交于 2020-01-06 12:50:54

问题


consider the following example

df1 <- data.frame(a=c(1,2,3),b=c(2,4,6));
transform(df1,c=a+b)
    a b c
  1 1 2 3
  2 2 4 6
  3 3 6 9

So far, so good. Now I would like to code this dynamically, using as.formula:

transform(df1,as.formula("c=a+b"))

However, R says

Error in eval(expr, envir, enclos) : object 'b' not found

This error does not occur using "~" as separator of left hand and right hand side. Can I somehow delay the evaluation of the formula? Is it possible at all to use as.formula on an assignment? I have tried fiddling around with 'with' but to no avail.


回答1:


I've solved the problem you mentioned in your comment, since that seems to be your real goal. This avoids messing with the formulae from your original question.

A reproducible version of your dataset.

group_names <- apply(
    expand.grid("X", c("X", "O", "Y"), c("A", "B", "C"), "_", 0:9, 0:9),
    1,
    paste,
    collapse = ""
)
n_groups <- 50
n_points_per_group <- 10
df1 <- as.data.frame(matrix(
    runif(n_points_per_group * n_groups),
    ncol = n_groups
))
colnames(df1) <- sample(group_names, n_groups)

Now convert the data frame to long format. (Using reshape package here. You could also use stats::reshape.)

melted_df1 <- melt(df1)

Define a grouping based upon your criteria that the second character and the number match.

melted_df1$group <- with(melted_df1, paste(
    substring(variable, 2, 2),    
    substring(variable, 5, 6),
    sep = ""
))

Now call tapply (or plyr::ddply if you prefer) to get the summary stats.

with(melted_df1, tapply(value, group, mean))


来源:https://stackoverflow.com/questions/9094731/as-formula-does-not-like-equivalence-object-not-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!