as.formula不喜欢等价的'='(找不到对象) [英] as.formula does not like equivalence '=' (object not found)

查看:203
本文介绍了as.formula不喜欢等价的'='(找不到对象)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下示例

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

到目前为止,太好了.现在,我想使用as.formula动态地对此进行编码:

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

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

但是,R说

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

使用〜"作为左手和右手的分隔符不会发生此错误.我可以以某种方式延迟对公式的评估吗?是否可以在作业中使用as.formula?我尝试摆弄'with',但无济于事.

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.

推荐答案

我已经解决了您在评论中提到的问题,因为这似乎是您的真正目标.这样可以避免弄乱您原始问题中的公式.

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.

数据集的可复制版本.

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)

现在将数据帧转换为长格式. (在这里使用reshape包.您也可以使用stats::reshape.)

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 = ""
))

现在调用tapply(如果需要,还可以调用plyr::ddply)以获取摘要统计信息.

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

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

这篇关于as.formula不喜欢等价的'='(找不到对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆