R语言 在mutate()中使用which()

uqjltbpv  于 2023-03-27  发布在  其他
关注(0)|答案(3)|浏览(177)

我一直在使用which()在mutate中定义一个新的变量。
我有两个 Dataframe :

df1 <- data.frame(
telephone = c("1231231234", "2342342345", "3453453456", "1231231234"),
email = c("a@email.com", "b@email.com", "c@email.com", "d@mail.com")
)

df2 <- data.frame(
phone = c("1231231234", "2342342345", "3453453456")
)

我试图做的是向df2添加一个新变量,该变量存储df1$telephone中出现“phone”值的每个行号。我尝试了以下操作:

df2 <- df2 %>%
mutate(
phone_ind = str_flatten(which(df1$telephone == phone), collapse = ", ")
)

这将产生警告

警告信息:计算phone_ind = str_flatten(which(df1$telephone == phone), collapse = ", ")时出现问题。
较长对象长度不是较短对象长度的倍数

以及以下明显错误的结果:

df2 <- data.frame(
phone = c("1231231234", "2342342345", "3453453456"),
phone_ind = c("1, 2, 3, 4", "1, 2, 3, 4", "1, 2, 3, 4")
)

有什么想法吗?提前感谢您的任何见解。

vtwuwzda

vtwuwzda1#

library(dplyr) # v1.1.0
df2 %>%
  left_join(transmute(df1, phone = telephone, row = row_number()), multiple = "all") %>%
  summarize(row = paste(row, collapse = ", "), .by = phone)

结果

Joining with `by = join_by(phone)`
       phone  row
1 1231231234 1, 4
2 2342342345    2
3 3453453456    3
twh00eeo

twh00eeo2#

您也可以先将行号添加到df1,然后将其连接到df2并折叠行号:

library(tidyverse)

df1 <- tibble(
  telephone = c("1231231234", "2342342345", "3453453456", "1231231234"),
  email = c("a@email.com", "b@email.com", "c@email.com", "d@mail.com")
)

df2 <- tibble(
  phone = c("1231231234", "2342342345", "3453453456")
)

df1 |> 
  mutate(row = row_number()) |> 
  select(!email) |> 
  right_join(df2, join_by(telephone == phone)) |> 
  summarise(rows = str_flatten(row, collapse = ", "), 
            .by = telephone)
#> # A tibble: 3 × 2
#>   telephone  rows 
#>   <chr>      <chr>
#> 1 1231231234 1, 4 
#> 2 2342342345 2    
#> 3 3453453456 3

创建于2023-03-21带有reprex v2.0.2

ajsxfq5m

ajsxfq5m3#

您可以在base R中使用sapplypaste(或者如果您更喜欢使用stringr包,则只需将paste更改为str_flatten

df2$new <- sapply(seq_len(nrow(df2)), function(x) {
  paste(rownames(df1[df1$telephone %in% df2$phone[x],]), collapse = ", ")
})

       phone  new
1 1231231234 1, 4
2 2342342345    2
3 3453453456    3

相关问题