gpt4 book ai didi

r - 如何在 R 中进行哈希调用

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

我有一个看起来像这样的数据框:

 n <- c("foo","bar","qux","qux","bar")
k <- c(100,200,300,400,500)
z <- c("z","w","x","y","v")
df1 <- data.frame(n,k,z)
df1
n k z
1 foo 100 z
2 bar 200 w
3 qux 300 x
4 qux 400 y
5 bar 500 v

给定第二个数据框
l <- c("k1","k2","k3","k4","k5")
n2 <- c("foo","bar","qux","qux","bar") # name difference of (n2) is intentional
df2 <- data.frame(n2,l)
n2 l
1 foo k1
2 bar k2
3 qux k3
4 qux k4
5 bar k5

我想创建具有以下条件的第三个数据框:

Use df1 as a source to create third dataframe and the checking reference is n for every row in df1 with respect to n2 of df2.



所以最后我想要这个:
  n   k z   call
1 foo 100 z k1
2 bar 200 w k2
3 qux 300 x k3
4 qux 400 y k3
5 bar 500 v k2

有什么办法呢?

最佳答案

我认为您正在寻找 match :

match returns a vector of the positions of (first) matches of its first argument in its second.


m <- df1
cbind(m,call=df2$l[match(df1$n ,df2$n2)])
n k z call
1 foo 100 z k1
2 bar 200 w k2
3 qux 300 x k3
4 qux 400 y k3
5 bar 500 v k2

另一种选择是使用 merge但你应该删除重复的:
hh <- merge(df1,df2,by.x='n',by.y='n2')
hh[!duplicated(hh[,1:3]),]
n k z l
1 bar 200 w k2
3 bar 500 v k2
5 foo 100 z k1
6 qux 300 x k3
8 qux 400 y k3

关于r - 如何在 R 中进行哈希调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17294011/

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