用R中另一列的值替换来自一列的多个观测值

时间:2019-05-25 10:23:58

标签: r join merge dplyr

我试图用另外两列中的值替换两列中的值。这是一个相当基本的问题,已被by python users询问,但是我使用的是R。

我有一个df看起来像这样(仅在更大范围内[> 20,000]):

squirrel_id    locx    locy    dist
6391           17.5    10.0    50.0
6391           17.5    10.0    20.0
6391           17.5    10.0    15.5
8443           20.5    1.0     800
6025           -5.0    -0.5    0.0

对于63只松鼠,我需要替换它们的locxlocy值。

我通常用以下代码替换值:

library(dplyr)    

df <- df %>%
   mutate(locx = ifelse (squirrel_id=="6391", "12.5", locx),
         locy = ifelse (squirrel_id=="6391", "15.5", locy),
         locx = ifelse (squirrel_id=="8443", "2.5", locx),
         locy = ifelse (squirrel_id=="8443", "80", locy)) #etc for 63 squirrels

哪个会给我的?

squirrel_id    locx    locy    dist
6391           12.5    10.0    50.0
6391           12.5    10.0    20.0
6391           12.5    10.0    15.5
8443           2.5     80.0    800
6025           -5.0    -0.5    0.0

但这会创建额外的126行代码,我怀疑有更简单的方法来实现这一目标。

我确实在单独的locx中拥有所有新的locydf值,但是我不知道如何将{{1 }},而不会弄乱数据。

dataframe的值需要替换旧squirrel_id中的值:

df

我如何才能更有效地做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以left_join两个数据帧,然后使用if_else语句获取正确的locxlocy。试试:

library(dplyr)
df %>% left_join(df2, by = "squirrel_id") %>%
        mutate(locx = if_else(is.na(new_locx), locx, new_locx), # as suggested by @echasnovski, we can also use locx = coalesce(new_locx, locx)
               locy = if_else(is.na(new_locy), locy, new_locy)) %>% # or locy = coalesce(new_locy, locy)
        select(-new_locx, -new_locy)
# output
  squirrel_id  locx locy  dist
1        6391  12.5 15.5  50.0
2        6391  12.5 15.5  20.0
3        6391  12.5 15.5  15.5
4        8443   2.5 80.0 800.0
5        6025 -55.0  0.0   0.0
6        5000  18.5 18.5  10.0 # squirrel_id 5000 was created for an example of id 
# present if df but not in df2

数据

df <- structure(list(squirrel_id = c(6391L, 6391L, 6391L, 8443L, 6025L, 
5000L), locx = c(17.5, 17.5, 17.5, 20.5, -5, 18.5), locy = c(10, 
10, 10, 1, -0.5, 12.5), dist = c(50, 20, 15.5, 800, 0, 10)), class = "data.frame", row.names = c(NA, 
-6L))
df2 <- structure(list(squirrel_id = c(6391L, 8443L, 6025L), new_locx = c(12.5, 
2.5, -55), new_locy = c(15.5, 80, 0)), class = "data.frame", row.names = c(NA, 
-3L))

答案 1 :(得分:0)

使用@ANG的数据,这是一个data.table解决方案。它通过引用连接并更新原始df

library(data.table)

setDT(df)
setDT(df2)

df[df2, on = c('squirrel_id'), `:=` (locx = new_locx, locy = new_locy) ]

df

   squirrel_id  locx locy  dist
1:        6391  12.5 15.5  50.0
2:        6391  12.5 15.5  20.0
3:        6391  12.5 15.5  15.5
4:        8443   2.5 80.0 800.0
5:        6025 -55.0  0.0   0.0
6:        5000  18.5 12.5  10.0

另请参阅:

how to use merge() to update a table in R

Replace a subset of a data frame with dplyr join operations

R: Updating a data frame with another data frame