r - 从其他数据集中替换数据集的数字列
问题描述
我想用相应转换数据集的数字列专门替换一个数据集的数字列。我该怎么做(不使用特定数据集的特定代码)?
例如mpg
图书馆中的玩具示例ggplot2
:
mpg0 <- mpg
set.seed(123)
mpg0[sample(nrow(mpg),70,replace=FALSE),3] <- NA
mpg0[sample(nrow(mpg),70,replace=FALSE),8] <- NA
mpg0[sample(nrow(mpg),70,replace=FALSE),9] <- NA
sampled <- sample(nrow(mpg),50,replace=FALSE)
mpg_test <- mpg0[sampled,]
mpg_train <- mpg0[-sampled,]
mpg_mean <- mpg_train %>% group_by(cyl) %>% summarise_if(is.numeric,mean,na.rm=TRUE)
temp1 <- mpg_test %>% left_join(mpg_mean, by = 'cyl')
现在我想用左连接对应列中的值替换mpg_test
(columns displ
, cty
, hwy
--there are no NAs in other numeric columns) 的数字列中的缺失值。我可以做到
temp1 <- as.data.frame(temp1)
temp1[c(3,8,9)][is.na(temp1[c(3,8,9)])] <- temp1[c(12,14,15)][is.na(temp[c(3,8,9)])]
但这是特定于该数据集的。问题mutate_if
是我不知道要放入什么函数。有没有一种很好的通用方法可以做到这一点,即改变数字列以获得平均值,将 NA 替换为来自相应左连接列的同一行中的值?
(请仅使用 dplyr)
解决方案
您可以通过更改左连接并使用来做到这一点case_when
:
library(dplyr)
temp1 <- left_join(mpg_test, mpg_mean, by = "cyl")
temp1 %>%
mutate_if(is.integer, as.numeric) %>%
mutate(displ.x =
case_when(
is.na(displ.x) ~ displ.y,
TRUE ~ displ.x
),
cty.x =
case_when(
is.na(cty.x) ~ cty.y,
TRUE ~ cty.x
),
hwy.x =
case_when(
is.na(hwy.x) ~ hwy.y,
TRUE ~ hwy.x
)) %>%
select(-c(displ.y, year.y, cty.y, hwy.y)) %>%
rename(displ = displ.x,
year = year.x,
cty = cty.x,
hwy = hwy.x)
推荐阅读
- iis - 如何在具有 SSR 优势的 IIS 上部署下一个 js 应用程序?
- elasticsearch - 用于查询 DSL 的 Elasticsearch Rest 客户端
- python - opencv-python 和 opencv-contrib-python 的区别
- typescript - 从枚举的 const 创建联合类型
- go - 如何检查响应标头是否包含某个字符串
- r - 如何对R中两个不相等向量的值求和?
- javascript - 带有服务器端处理的 Shiny App 中的 JS 回调
- r - R 新手,在我的函数中收到错误
- c# - 如何将选定的索引从列表框显示到文本框
- spring-cloud-stream - 处理失败时重新排队 Kinesis 消息