r - 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)
解决方案
您的样本数据:
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 提供索引。
推荐阅读
- r - 按名称汇总跨多个变量的数据
- c# - AWS Toolkit for Visual Studio 错误?AWS C# lambda 加载 Kafka 的 librdkafka 原生库失败?
- oracle-apex - Oracle APEX - APEX_ITEM.SELECT_LIST 未显示所需结果
- scala - 在 scala 中是否可以动态传递泛型类型?
- sql - 如何通过 DB2 中的表过滤硬编码列表?
- java - 没有游标或循环的 Oracle 函数
- python - 来自数据框的嵌套字典,带有循环列表
- django - Django:无法通过foreign_key访问模板上的数据
- windows - Microsoft Windows 上的 DisabledByDefault 和 Enabled SSL/TLS 注册表项有什么区别?
- python - 相同 For 循环和列表理解的不同输出