如何使用另一个数据帧中的值替换变量的NA

时间:2015-02-23 18:13:27

标签: r match dplyr na

我希望这个不是傻瓜。

我有两个带有变量ID和性别/性别的数据帧。在df1中,有NA。在df2中,变量已完成。我想用df2中的值完成df1中的列。 (在df1中,变量称为“性别”。在df2中,它被称为“性别”。)

这是我到目前为止所尝试的内容:

#example-data
ID<-seq(1,30,by=1)
df1<-as.data.frame(ID)
df2<-df1
df1$gender<-c(NA,"2","1",NA,"2","2","2","2","2","2",NA,"2","1","1",NA,"2","2","2","2","2","1","2","2",NA,"2","2","2","2","2",NA)
df2$sex<-c("2","2","1","2","2","2","2","2","2","2","2","2","1","1","2","2","2","2","2","2","1","2","2","2","2","2","2","2","2","2")


#Approach 1: 
NAs.a <- is.na(df1$gender)
df1$gender[NAs.a] <- df2[match(df1$ID[NAs.a], df2$ID),]$sex

#Approach 2 (i like dplyr a lot, perhaps there´s a way to use it):
library("dplyr")
temp<-df2 %>% select(ID,gender)

#EDIT:
#df<-left_join(df1$gender,df2$gender, by="ID") 
 df<-left_join(df1,df2, by="ID") 

非常感谢。

3 个答案:

答案 0 :(得分:3)

以下是使用data.table二进制加入的快速解决方案,这将只加入 gender sex并保持所有其余列不变

library(data.table)
setkey(setDT(df1), ID)
df1[df2, gender := i.sex][]
#     ID gender
#  1:  1      2
#  2:  2      2
#  3:  3      1
#  4:  4      2
#  5:  5      2
#  6:  6      2
#  7:  7      2
#  8:  8      2
#  9:  9      2
# 10: 10      2
# 11: 11      2
# 12: 12      2
# 13: 13      1
# 14: 14      1
# 15: 15      2
# 16: 16      2
# 17: 17      2
# 18: 18      2
# 19: 19      2
# 20: 20      2
# 21: 21      1
# 22: 22      2
# 23: 23      2
# 24: 24      2
# 25: 25      2
# 26: 26      2
# 27: 27      2
# 28: 28      2
# 29: 29      2
# 30: 30      2

答案 1 :(得分:2)

你可以做到

df1 %>% select(ID) %>% left_join(df2, by = "ID")
#   ID sex
#1   1   2
#2   2   2
#3   3   1
#4   4   2
#5   5   2
#6   6   2
#.. ..  

这假设 - 如示例中 - 来自df1的所有ID也存在于df2中并且在那里具有性别/性别信息。


如果您的数据中还有其他列,您也可以尝试这样做:

df1 %>% select(-gender) %>% left_join(df2[c("ID", "sex")], by = "ID")

答案 2 :(得分:1)

对于基础R来说,这可能是最简单的。

idx <- is.na(df1$gender)
df1$gender[idx] = df2$sex[idx]