gpt4 book ai didi

r - 合并异构数据帧

转载 作者:行者123 更新时间:2023-12-04 19:52:23 26 4
gpt4 key购买 nike

我正在尝试合并两个 data.frames在 R 中

d1 <- data.frame(Id=1:3,Name=c("Yann","Anne","Sabri"),Age=c(21,19,31),Height=c(178,169,192),Grade=c(15,12,18))
d2 <- data.frame(Id=c(1,3,4),Name=c("Yann","Sabri","Jui"),Age=c(28,21,15),Sex=c("M","M","F"),City=c("Paris","Paris","Toulouse"))

我想在 Id 之前合并, 并且只保留 Id , Name , Age , SexGrade决赛中的栏目 data.frame .

我想出了一个冗长的代码来完成这项工作,但有没有更好的方法?

dm <- data.frame(Id=unique(c(d1$Id,d2$Id)))
dm.d1.rows <- sapply(dm$Id, match, table = d1$Id)
dm.d2.rows <- sapply(dm$Id, match, table = d2$Id)
for(i in c("Name", "Age","Sex","Grade")) {
if(i %in% colnames(d1) && is.factor(d1[[i]]) || i %in% colnames(d2) && is.factor(d2[[i]])) dm[[i]]<- factor(rep(NA,nrow(dm)),
levels=unique(c(levels(d1[[i]]),levels(d2[[i]]))))
else dm[[i]]<- rep(NA,nrow(dm))
if(i %in% colnames(d1)) dm[[i]][!is.na(dm.d1.rows)] <- d1[[i]][na.exclude(dm.d1.rows)]
if(i %in% colnames(d2)) dm[[i]][!is.na(dm.d2.rows)] <- d2[[i]][na.exclude(dm.d2.rows)]
}

最佳答案

这是来自 的想法,使用函数 coalesce。此函数基本上将 NA 值替换为另一个(指定的)列的值。 - 您可以找到函数 coalesce 的更多信息和实现 here

Official Documentation for coalesce: Given a set of vectors, coalesce() finds the first non-missing value at each position. This is inspired by the SQL COALESCE function which does the same thing for NULLs.


library(tidyverse)

d1 %>%
full_join(d2, by = c('Id', 'Name')) %>%
mutate(Age = coalesce(Age.x, Age.y)) %>%
select(Id, Name, Age, Sex, Grade)

这给出了,

  Id  Name Age  Sex Grade
1 1 Yann 21 M 15
2 2 Anne 19 <NA> 12
3 3 Sabri 31 M 18
4 4 Jui 15 F NA

同样,在语法,

library(data.table)

#Convert to data.tables
d1_t <- setDT(d1)
d2_t <- setDT(d2)

merge(d1_t, d2_t, by = c('Id', 'Name'), all = TRUE)[,
Age := ifelse(is.na(Age.x), Age.y, Age.x)][,
c('Age.x', 'Age.y', 'City', 'Height') := NULL][]

这给出了,

   Id  Name Grade  Sex Age
1: 1 Yann 15 M 21
2: 2 Anne 12 <NA> 19
3: 3 Sabri 18 M 31
4: 4 Jui NA F 15

关于r - 合并异构数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52476396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com