使用dplyr加入两个数据帧时,可以替换NAs吗? [英] Can I replace NAs when joining two data frames with dplyr?
问题描述
NA
条目。这是一个简化的例子: df1< - data.frame(fruit = c('apples','oranges' '香蕉','葡萄'),var1 = c(1,2,3,4),var2 = c(3,NA,6,NA),stringsAsFactors = FALSE)
df2< - data.frame (fruit = c('oranges','grapes'),var2 = c(5,6),var3 = c(7,8),stringsAsFactors = FALSE)
我可以使用dplyr加入函数来加入这些数据帧,并自动确定非 NA
条目的优先级,以便我获取var2列在连接的数据框中没有 NA
条目?现在,如果我调用 left_join
,它保留 NA
条目,如果我调用 full_join
它会重复行。
coalesce
可能是你需要的东西。它从第一个向量填充NA,其值位于相应位置的第二个向量:
library(dplyr)
df1%>%
left_join(df2,by =fruit)%>%
mutate(var2 = coalesce(var2.x,var2.y))%>%
选择(-var2.x,-var2.y)
#fruit var1 var3 var2
#1 apples 1 NA 3
#2 oranges 2 7 5
# 3香蕉3 NA 6
#4葡萄4 8 6
或使用 data.table
,代替:
library(data.table)
setDT(df1)[setDT(df2),on =fruit,`:=`(var2 = i.var2,var3 = i.var3)]
df1
#fruit var1 var2 var3
#1:apples 1 3 NA
#2:橘子2 5 7
#3:香蕉3 6 NA
#4:葡萄4 6 8
I would like to join two data frames. Some of the column names overlap, and there are NA
entries in one of the data frame's overlapping columns. Here is a simplified example:
df1 <- data.frame(fruit = c('apples','oranges','bananas','grapes'), var1 = c(1,2,3,4), var2 = c(3,NA,6,NA), stringsAsFactors = FALSE)
df2 <- data.frame(fruit = c('oranges','grapes'), var2=c(5,6), var3=c(7,8), stringsAsFactors = FALSE)
Can I use dplyr join functions to join these data frames and automatically prioritize the non-NA
entry so that I get the "var2" column to have no NA
entries in the joined data frame? As it is now, if I call left_join
, it keeps the NA
entries, and if I call full_join
it duplicates the rows.
coalesce
might be something you need. It fills the NA from the first vector with values from the second vector at corresponding positions:
library(dplyr)
df1 %>%
left_join(df2, by = "fruit") %>%
mutate(var2 = coalesce(var2.x, var2.y)) %>%
select(-var2.x, -var2.y)
# fruit var1 var3 var2
# 1 apples 1 NA 3
# 2 oranges 2 7 5
# 3 bananas 3 NA 6
# 4 grapes 4 8 6
Or use data.table
, which does in-place replacing:
library(data.table)
setDT(df1)[setDT(df2), on = "fruit", `:=` (var2 = i.var2, var3 = i.var3)]
df1
# fruit var1 var2 var3
# 1: apples 1 3 NA
# 2: oranges 2 5 7
# 3: bananas 3 6 NA
# 4: grapes 4 6 8
这篇关于使用dplyr加入两个数据帧时,可以替换NAs吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!