仅在数据框中保留某些预测变量组合

Only Keep Certain Combinations of Predictors in a Dataframe

假设我有一个这样的数据框:

> col1 <- rep(1:3,10)
> col2 <- rep(c("a","b"),15)
> col3 <- rnorm(30,10,2)
> sample_df <- data.frame(col1 = col1, col2 = col2, col3 = col3)
> head(sample_df)
  col1 col2      col3
1    1    a 13.460322
2    2    b  3.404398
3    3    a  8.952066
4    1    b 11.148271
5    2    a  9.808366
6    3    b  9.832299

我只想保留 col3 标准差低于 2 的预测变量组合。我可以使用 ddply 找到这些组合,但我不知道如何回溯到原始 DF 和 select 正确的级别。

> sample_df_summ <- ddply(sample_df, .(col1, col2), summarize, sd = sd(col3), count = length(col3))
> head(sample_df_summ)
  col1 col2       sd count
1    1    a 2.702328     5
2    1    b 1.032371     5
3    2    a 2.134151     5
4    2    b 3.348726     5
5    3    a 2.444884     5
6    3    b 1.409477     5

为清楚起见,在此示例中,我希望 DF 具有 col1 = 3、col2 = b 和 col1 = 1 以及 col 2 = b。我该怎么做?

您可以添加一个 "keep" 列,该列只有在标准差低于 2 时才为 TRUE。然后,您可以使用左连接(合并)将 "keep" 列添加到初始数据框。最后,您只需 select 保持等于 TRUE。

# add the keep column
sample_df_summ$keep <- sample_df_summ$sd < 2
sample_df_summ$sd <- NULL
sample_df_summ$count <- NULL

# join and select the rows
sample_df_keep <- merge(sample_df, sample_df_summ, by = c("col1", "col2"), all.x = TRUE, all.y = FALSE)
sample_df_keep <- sample_df_keep[sample_df_keep$keep, ]
sample_df_keep$keep <- NULL

使用dplyr:

library(dplyr)
sample_df %>% group_by(col1, col2) %>% mutate(sd = sd(col3)) %>% filter(sd < 2)

你得到:

#Source: local data frame [6 x 4]
#Groups: col1, col2
# 
#  col1 col2      col3        sd
#1    1    a 10.516437 1.4984853
#2    1    b 11.124843 0.8652206
#3    2    a  7.585740 1.8781241
#4    3    b  9.806124 1.6644076
#5    1    a  7.381209 1.4984853
#6    1    b  9.033093 0.8652206