【问题标题】:Create prediction grid from dplyr piping从 dplyr 管道创建预测网格
【发布时间】:2017-03-30 16:59:48
【问题描述】:

我希望有人有一个解决方案,可以在使用 dplyr 的管道中使用某种形式的expand.grid。我正在做一些建模,其中我有几个不同的组(或下面的类型),并且这些组有不同的 x & y 数据范围。一旦我对数据进行游戏,我就有兴趣为预测创建一个图,但我只想预测每个值占据的范围内的值,而不是数据集的整个范围。

我已经在下面发布了一个工作示例,但我想知道是否有办法使用循环绕过并完成我的任务。

干杯

require(ggplot2)
require(dplyr)

# Create some data
df  = data.frame(Type = rep(c("A","B"), each = 100),
                 x = c(rnorm(100, 0, 1), rnorm(100, 2, 1)),
                 y = c(rnorm(100, 0, 1), rnorm(100, 2, 1)))

# and if you want to check out the data
ggplot(df,aes(x,y,col=Type)) + geom_point() + stat_ellipse()

# OK so I have no issue extracting the minimum and maximum values 
# for each type
df_summ = df %>%
  group_by(Type) %>%
  summarize(xmin = min(x),
            xmax = max(x),
            ymin = min(y),
            ymax = max(y))
df_summ

# and I can create a loop and use the expand.grid function to get my 
# desired output
test = NULL
for(ii in c("A","B")){
  df1 = df_summ[df_summ$Type == ii,]
  x = seq(df1$xmin, df1$xmax, length.out = 10)
  y = seq(df1$ymin, df1$ymax, length.out = 10)
  coords = expand.grid(x = x, y = y)
  coords$Type = ii
  test = rbind(test, coords)
}

ggplot(test, aes(x,y,col = Type)) + geom_point()

但我真正想做的是找到绕过循环的方法 并尝试直接从我的管道操作员那里获得相同的输出。 我使用 do() 函数尝试了一些组合,但没有效果, 而下面发布的只是众多失败尝试中的一种

df %>%
  group_by(Type) %>%
  summarize(xmin = min(x),
            xmax = max(x),
            ymin = min(y),
            ymax = max(y)) %>%
  do(data.frame(x = seq(xmin, xmax, length.out = 10),
                y = seq(ymin, ymax, length.out = 10)))

# this last line returns an error
# Error in is.finite(from) : 
#   default method not implemented for type 'closure'

【问题讨论】:

  • 您可能对modelr包中的data_grid()seq_range()感兴趣,它们的使用说明了here

标签: r dplyr


【解决方案1】:

您的do() 尝试几乎是正确的。诀窍只是在汇总后重新分组(这似乎放弃了分组)。您还需要确保使用.$ 从链中的数据中获取值。试试这个

test <- df %>%
  group_by(Type) %>%
  summarize(xmin = min(x),
            xmax = max(x),
            ymin = min(y),
            ymax = max(y)) %>%
  group_by(Type) %>%
  do(expand.grid(x = seq(.$xmin, .$xmax, length.out = 10),
                y = seq(.$ymin, .$ymax, length.out = 10)))
ggplot(test, aes(x,y,col = Type)) + geom_point()

【讨论】:

  • 非常感谢您。我想我尝试了一些非常相似的东西,但是在尝试获取值时我错过了.$
【解决方案2】:

使用modelr 包中的data_grid 函数,这是一种方法:

library(dplyr)
library(modelr)

df %>%
   group_by(Type) %>%
   data_grid(x, y) %>%
ggplot(aes(x,y, color = Type)) + geom_point()

此方法为每个组中的每个 x 值和每个 y 值生成一个包含 xy 对的行。因此,结果数据框中的每个 x-y 对仅基于实际出现在数据中的 xy 的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 2017-05-29
    • 2022-11-12
    相关资源
    最近更新 更多