使用dplyr管道创建预测网格

3
我希望有人能够解决使用dplyr管道中的某种形式的expand.grid的问题。我正在进行一些建模工作,其中我有几个不同的组(或下面的类型),这些组具有不同的x和y数据范围。一旦我在数据上运行了gam,我就想创建一个预测图,但我只想预测每个值占据的范围内的值,而不是整个数据集的范围。
我已经在下面发布了一个可行的示例,但我想知道是否有一种方法可以避免使用循环并完成我的任务。
干杯
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()感兴趣,它们的使用方法在这里有详细说明:链接 - bschneidr
2个回答

2

你的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()

enter image description here


非常棒,非常感谢。我认为我尝试了非常相似的东西,但是在尝试获取值时我错过了 .$ - s_scolary

1
使用 modelr 包中的 data_grid 函数,以下是一种实现方法:
library(dplyr)
library(modelr)

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

enter image description here

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接