[英]In R dplyr, gsub() in mutate() using column as the pattern
zed = data.frame(name = c('Tom', 'Joe', 'Nick', 'Bill'), names = c('TomRyanTim', 'RobJoeMike', 'SteveKevinNick', 'EvanPacJimmy'), stringsAsFactors = FALSE)
> zed
name names
1 Tom TomRyanTim
2 Joe RobJoeMike
3 Nick SteveKevinNick
4 Bill EvanPacJimmy
> zed %>% dplyr::mutate(names = gsub(name, '', names))
name names
1 Tom RyanTim
2 Joe RobJoeMike
3 Nick SteveKevinNick
4 Bill EvanPacJimmy
Warning message:
Problem with `mutate()` column `names`.
ℹ `names = gsub(name, "", names)`.
ℹ argument 'pattern' has length > 1 and only the first element will be used
在上面的示例中, mutate(gsub())
似乎試圖在每一行中對名稱Tom
進行 gsub,而我希望對每一行 gsub() 在name
列中的值。 我們正在尋找以下 output:
output$names = c('RyanTim', 'RobMike', SteveKevin', 'EvanPacJimmy')
是否可以更新我們的代碼以使 mutate + gsub 正常運行?
rowwise
:
zed %>%
rowwise() %>%
mutate(names = gsub(name, '', names)) %>%
ungroup()
為避免使用rowwise
,您可以使用stringr::str_replace_all
或stringr::str_remove_all
:
library(stringr)
zed %>%
mutate(names = str_replace_all(names, name, ""),
names = str_remove_all(names, name))
name names
<chr> <chr>
1 Tom RyanTim
2 Joe RobMike
3 Nick SteveKevin
4 Bill EvanPacJimmy
或group_by
:
library(dplyr)
zed |>
group_by(name, names) |>
mutate(names = gsub(name, "", names)) |>
ungroup()
Output:
# A tibble: 4 × 2
name names
<chr> <chr>
1 Tom RyanTim
2 Joe RobMike
3 Nick SteveKevin
4 Bill EvanPacJimmy
另一種方法是使用sapply
遍歷您的zed
數據框,並在其中使用gsub
。
library(dplyr)
zed %>%
mutate(names = sapply(1:nrow(.), \(x) gsub(.[x, 1], "", .[x, 2])))
name names
1 Tom RyanTim
2 Joe RobMike
3 Nick SteveKevin
4 Bill EvanPacJimmy
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.