gpt4 book ai didi

r - 在 r 中加入多个数据框

转载 作者:行者123 更新时间:2023-12-01 23:48:45 25 4
gpt4 key购买 nike

a1 <- data.frame(id=c(1,1,1,1,2,2,2,3,3),
var=c("6402","1","1","3","6406","6406","2","1","1"))
b1 <- data.frame(var=c("6402","6406"),
txt=c("A","B"))
n1 <- data.frame(id=c(1,2,3))


desired <- data.frame(id=c(1,2,3),
txt=c("A","B",NA))

如何连接 a1、b1 和 n1 以生成所需的 df?

最佳答案

我们可以使用tidyverse

library(dplyr)
distinct(a1) %>%
left_join(b1, by = 'var') %>%
full_join(n1) %>%
group_by(id) %>%
summarise(txt = first(txt))
# A tibble: 3 x 2
# id txt
# <dbl> <chr>
#1 1 A
#2 2 B
#3 3 <NA>

或者使用data.table

unique(setDT(a1))[b1,  txt := txt, on = .(var)][n1, .SD[1],
on = .(id), by = .EACHI][, var := NULL][]

关于r - 在 r 中加入多个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63784134/

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