我試圖找到一種方法來搜索字串,例如“Prep”,然后用特定值替換下面行中的單元格,例如“SINGLE”。
這是我的示例輸入和輸出。我可以在 $V4 中 grep 并找到值,但我似乎無法弄清楚如何用我想要的文本替換下面的行。
誰能給我一個提示我做錯了什么?我嘗試了許多 mutate 函式,但找不到一個可以作業。
input = structure(list(V1 = c("Fred", "", "John", "", "Max", "", "Tim",
""), V2 = c("Chicago", "", "Boston", "", "London", "", "Paris",
""), V3 = c("", "Red", "", "Yellow", "", "Red", "", "Blue"),
V4 = c("Final", "TEAM", "Prep", "TEAM", "Prep", "TEAM", "Final",
"SINGLE")), row.names = c(NA, 8L), class = "data.frame")
output = structure(list(V1 = c("Fred", "", "John", "", "Max", "", "Tim",
""), V2 = c("Chicago", "", "Boston", "", "London", "", "Paris",
""), V3 = c("", "Red", "", "Yellow", "", "Red", "", "Blue"),
V4 = c("Final", "TEAM", "Prep", "SINGLE", "Prep", "SINGLE",
"Final", "SINGLE")), row.names = 9:16, class = "data.frame")
uj5u.com熱心網友回復:
這是一種基于lag()dplyr 包(https://dplyr.tidyverse.org/reference/lead-lag.html)中的功能的潛在方法:
library(dplyr)
input <- structure(list(V1 = c("Fred", "", "John", "", "Max", "", "Tim",
""), V2 = c("Chicago", "", "Boston", "", "London", "", "Paris",
""), V3 = c("", "Red", "", "Yellow", "", "Red", "", "Blue"),
V4 = c("Final", "TEAM", "Prep", "TEAM", "Prep", "TEAM", "Final",
"SINGLE")), row.names = c(NA, 8L), class = "data.frame")
output <- structure(list(V1 = c("Fred", "", "John", "", "Max", "", "Tim",
""), V2 = c("Chicago", "", "Boston", "", "London", "", "Paris",
""), V3 = c("", "Red", "", "Yellow", "", "Red", "", "Blue"),
V4 = c("Final", "TEAM", "Prep", "SINGLE", "Prep", "SINGLE",
"Final", "SINGLE")), row.names = 9:16, class = "data.frame")
answer <- input %>%
mutate(V4 = ifelse(lag(V4, default = first(V4)) == "Prep", "SINGLE", V4))
all_equal(output, answer)
#> [1] TRUE
由reprex 包于 2022-11-10 創建(v2.0.1)
這能解決你的問題嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/530788.html
標籤:rdplyr
上一篇:常用的正則運算式
