2

这里一定有一个模式/理由,但我就是看不到它。您如何第一次正确引用变量?

require(ggplot2)
require(reshape2)
require(plyr)

# reshape2

# These work.
dcast(mpg, manufacturer ~ class, mean, value.var = "cty")
dcast(mpg, "manufacturer ~ class", mean, value.var = "cty")

# These don't.
dcast(mpg, .(manufacturer ~ class), mean, value.var = "cty")
dcast(mpg, manufacturer ~ class, mean, value.var = cty)
dcast(mpg, manufacturer ~ class, mean, value.var = .(cty))


# plyr

# These work.
ddply(mpg, .(manufacturer), summarize, mean = mean(cty))
ddply(mpg, "manufacturer", summarize, mean = mean(cty))
ddply(mpg, manufacturer ~ class, summarize, mean = mean(cty))

# These don't.
ddply(mpg, manufacturer, summarize, mean = mean(cty))
ddply(mpg, .(manufacturer), summarize, mean = mean(.(cty)))
ddply(mpg, .(manufacturer), summarize, mean = mean("cty"))
ddply(mpg, .(manufacturer ~ class), summarize, mean = mean(cty))
ddply(mpg, "manufacturer ~ class", summarize, mean = mean(cty))


# ggplot

# This works
qplot(displ, hwy, data = mpg)

# These don't
qplot(.(displ), .(hwy), data = mpg)
qplot("displ", "hwy", data = mpg)

p <- qplot(displ, hwy, data = mpg)

# These work
p + facet_wrap(~ cyl)
p + facet_wrap(.(cyl))
p + facet_wrap("cyl")

# This doesn't
p + facet_wrap(cyl)

随意添加任何缺少的排列和组合。

4

1 回答 1

0

参数格式完全取决于函数实现。通常,功能帮助页面描述了您必须提供它们的方式。

从 中获取ddply函数plyr。第二个参数被调用.variables并描述为:

.variables:用于拆分数据帧的变量,如“as.quoted”变量、公式或字符向量

这就是为什么您可以将它们输入为.(manufacturer)as.quoted变量)、"manufacturer"(字符向量)或manufacturer~class(公式)。

您有时可以判断它们不一致,但要知道如何引用参数,您必须了解函数的工作方式以及它期望的输入......

于 2013-10-07T09:16:12.613 回答