首页 > 解决方案 > r:随机替换一定数量的缺失值

问题描述

我有一列有很多缺失值。我想用一个数字随机替换其中一些缺失值(不是全部!),而另一些则用另一个数字替换。

示例:具有 10000 个值的列,其中一些值缺失。从这些缺失值中,随机选择 50 个并从 NA 更改为 1。另外,随机选择另外 30 个缺失值并从 NA 更改为 5。

我试过的:

rows<- test1[test1== NA]
rows_to_replace<-sample (rows, 30, REPLACE = FALSE)
test1[rows_to_replace,]<-5

但我无法让它工作。

一些样本数据

test1<-sample(c(0.5:10, NA), 10000, replace = T)

标签: r

解决方案


您的样本数据:

test1 <- sample(c(0.5:10, NA), 10000, replace = T)

随机选择 50 个 NA 并替换为 1:

na_test1 <- which(is.na(test1))
test1[sample(na_test1,50)] <- 1

随机选择另外 30 个并替换为 5 个:

na_test1 <- which(is.na(test1))
test1[sample(na_test1,30)] <- 5

将您的解决方案与我的解决方案进行比较,我们几乎做了同样的事情。该功能which()是这里的关键,为 NA 提供索引。


推荐阅读