gpt4 book ai didi

从left_join删除相同的列

转载 作者:行者123 更新时间:2023-12-04 10:57:20 24 4
gpt4 key购买 nike

我想通过id合并两个数据框,但是它们都具有2个相同的列;因此,当我合并时,我会得到新的.x.y列。如何将这两个数据帧与left_join()合并,并删除当前在我的代码中相同的额外列(`element.x,day.x,element.y和day.y),并保留一个列。

代码:

# Sample data
df1 <- data.frame(id = seq(1,5), value1 = rnorm(5), element = "TEST1", day = 15)
df2 <- data.frame(id = seq(1,5), value2 = rnorm(5), element = "TEST1", day = 15)

# Merge
df <- left_join(df1, df2, by = "id")

# Output
id value1 element.x day.x value2 element.y day.y
1 1 -0.69700149 TEST1 15 1.4324220 TEST1 15
2 2 -0.25514949 TEST1 15 0.7281354 TEST1 15
3 3 0.09206902 TEST1 15 0.8148839 TEST1 15
4 4 2.51799237 TEST1 15 1.3919671 TEST1 15
5 5 -0.77049050 TEST1 15 -0.2707201 TEST1 15

最佳答案

只需从df2中删除您不需要的所有内容-在这种情况下,就可以使用idvalue2列:

left_join(df1, select(df2, c(id,value2)), by = "id")

# id value1 element day value2
#1 1 1.2276303 TEST1 15 -0.1389861
#2 2 -0.8017795 TEST1 15 -0.5973131
#3 3 -1.0803926 TEST1 15 -2.1839668
#4 4 -0.1575344 TEST1 15 0.2408173
#5 5 -1.0717600 TEST1 15 -0.2593554

请注意,并非所有这些答案都是等效的,并询问结果是什么。例如。:
df1 <- data.frame(id=1:3,day=2:4,element=3:5,value1=100:102)
df2 <- data.frame(id=1:3,day=3:5,element=4:6,value2=200:202)
df1

# id day element value1
#1 1 2 3 100
#2 2 3 4 101
#3 3 4 5 102

df2
# id day element value2
#1 1 3 4 200
#2 2 4 5 201
#3 3 5 6 202

left_join(df1, df2)
#Joining by: c("id", "day", "element")
# id day element value1 value2
#1 1 2 3 100 NA
#2 2 3 4 101 NA
#3 3 4 5 102 NA

left_join(df1, select(df2, c(id,value2)), by = "id")
# id day element value1 value2
#1 1 2 3 100 200
#2 2 3 4 101 201
#3 3 4 5 102 202

关于从left_join删除相同的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33887978/

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