首页 > 解决方案 > 从其他数据集中替换数据集的数字列

问题描述

我想用相应转换数据集的数字列专门替换一个数据集的数字列。我该怎么做(不使用特定数据集的特定代码)?

例如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)

标签: rdplyr

解决方案


您可以通过更改左连接并使用来做到这一点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)

推荐阅读