【问题标题】:Replacing missing values with mean from another dataset, by factor用另一个数据集中的平均值替换缺失值,按因子
【发布时间】:2020-09-04 01:47:38
【问题描述】:

我有一个像iris 这样的数据框,我将把它分成训练集和测试集。以前,我可以使用 dplyr 中的 group_by 和 mutate 将每个属性的缺失值的平均值替换为属性中该物种的平均值。

我现在意识到,正确的 ML 练习需要首先分为训练和测试,然后我应该使用训练方法来估算测试集的平均值。

有人可以帮忙吗?

如果不清楚,我们以iris为例。

iris0 <- iris

iris0[sample(150,50,replace=FALSE),1] <- NA
iris0[sample(150,50,replace=FALSE),2] <- NA
iris0[sample(150,50,replace=FALSE),3] <- NA
iris0[sample(150,50,replace=FALSE),4] <- NA

set.seed(123)
sampled <- sample(150,50,replace=FALSE)
iris_test <- iris0[sampled,]
iris_train <- iris0[-sampled,]

现在我们来进行插补。我可以在 iris_train 中按类获取方法:

iris_train %>% group_by(Species) %>% summarise_all(mean,na.rm=TRUE)

1 setosa          5.07        3.49         1.5 
2 versica         5.89        2.84         4.33
3 virginica       6.56        2.97         5.52

现在,正如我所说,使用这些方法在 iris_train 中填充 NA 可以使用 dplyr(分组和变异)来完成。但我想用相同的方式替换 iris_test 中的 NA,即 setosa 物种用 5.07 填写 Sepal.Length 列中的任何 NA, versica 物种用 5.89 填写,virginica 填写任何 NA 在Sepal.Width 列与 2.97 等。

请仅使用 base-R 和 dplyr!

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    我们可以将平均值的结果存储在iris_mean、left_join 中,并用iris_test 替换NA 值。

    iris_mean <- iris_train %>% group_by(Species) %>% summarise_all(mean,na.rm=TRUE)
    temp <- iris_test %>%  left_join(iris_mean, by = 'Species')
    col1 <- 1:4
    col2 <- 6:9
    temp[col1][is.na(temp[col1])] <- temp[col2][is.na(temp[col1])]
    temp[1:5]
    

    【讨论】:

    • 正如我所说,我知道该怎么做。我想知道如何使用 iris_train 的方法来替换 iris_test 中的 NA。这是正确的统计做法
    猜你喜欢
    • 2019-09-17
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 2012-05-03
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多