gpt4 book ai didi

r - 使用R中的match函数按原样获得nomatch返回值

转载 作者:行者123 更新时间:2023-12-04 05:49:37 28 4
gpt4 key购买 nike

我有一个更大的现有数据框。对于这个较小的示例,我想根据“第一”列用newstate(df2)替换某些变量(替换状态(df1))。我的问题是,由于新数据帧(df2)中只有某些名称匹配,因此值以NA形式返回。

现有数据框:

state = c("CA","WA","OR","AZ")
first = c("Jim","Mick","Paul","Ron")
df1 <- data.frame(first, state)

first state
1 Jim CA
2 Mick WA
3 Paul OR
4 Ron AZ

新数据框与现有数据框匹配
state = c("CA","WA")
newstate = c("TX", "LA")
first =c("Jim","Mick")
df2 <- data.frame(first, state, newstate)

first state newstate
1 Jim CA TX
2 Mick WA LA

尝试使用匹配,但在原始数据帧中未找到df2中匹配的“第一个”变量的情况下,为“状态”返回NA。
df1$state <- df2$newstate[match(df1$first, df2$first)]

first state
1 Jim TX
2 Mick LA
3 Paul <NA>
4 Ron <NA>

有没有办法忽略不匹配或让不匹配按原样返回现有变量?这将是预期结果的示例:Jim/Mick的状态被更新,而Paul和Ron的状态没有改变。
      first state
1 Jim TX
2 Mick LA
3 Paul OR
4 Ron AZ

最佳答案

这是你想要的吗;顺便说一句,除非您真的想使用因子,否则请在data.frame调用中使用stringsAsFactors = FALSE。请注意在match调用中使用nomatch = 0。

> state = c("CA","WA","OR","AZ")
> first = c("Jim","Mick","Paul","Ron")
> df1 <- data.frame(first, state, stringsAsFactors = FALSE)
> state = c("CA","WA")
> newstate = c("TX", "LA")
> first =c("Jim","Mick")
> df2 <- data.frame(first, state, newstate, stringsAsFactors = FALSE)
> df1
first state
1 Jim CA
2 Mick WA
3 Paul OR
4 Ron AZ
> df2
first state newstate
1 Jim CA TX
2 Mick WA LA
>
> # create an index for the matches
> indx <- match(df1$first, df2$first, nomatch = 0)
> df1$state[indx != 0] <- df2$newstate[indx]
> df1
first state
1 Jim TX
2 Mick LA
3 Paul OR
4 Ron AZ

关于r - 使用R中的match函数按原样获得nomatch返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26189267/

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