我有一个数据框架,我想在其中一个列中更改一些值。
列值如下所示:
1“软珊瑚”“软珊瑚”8“软珊瑚”“软珊瑚”"..5“"..5”"..5“"..5”"..5“ "..5“、"..5”、"..5“、"..5”、"..6“、"..6”、"..6“ 22 "..6“"..6”"..6“"..6”"..6“"..6”"..7“ 29 "..7“"..7”"..7“"..7”"..7“"..7”"..7“ 36 "..7“"..8”"..8“"..8”"..8“"..8”"..8“ 43 "..8“"..8”"..8“"..9”"..9“"..9”"..9“ 50 "..9“"..9”"..9“"..9”"..9“"..10”"..10“ 57 "..10“"..10”"..10“"..10”"..10“"..10”"..10“ 64 "..11“"..11”"..11“"..11”"..11“"..11”"..11“ 71 "..11“"..11”“海扇”“海扇” 78名“海迷”"..13“"..13”"..13“ 85 "..13“"..13”"..13“"..13”"..13“"..13”"..14“ 92 "..14“、"..14”、"..14“、"..14”、"..14“、"..14”、"..14“ 99 "..14“
我想用前面的值替换数字,比如“软珊瑚”或“海扇”,视位置而定。
我的代码看起来如下(啊是数据帧obj,cor_type是列名):
ah <- ah %>% mutate(cor_n = case_when(stringi::stri_detect(str = cor_type, regex = "\\.") ~lag(cor_type),
TRUE ~ cor_type
)
)
但是,这只会更改regex匹配的第一个实例,即第9行。其余的值保持不变。我想我对mutate
工作方式的假设是错误的?PS:我不想写一个for循环。
发布于 2019-03-11 06:50:16
我不认为case_when
是最好的选择。一种方法是将replace
值与模式(\\.
)转换为NA
,然后使用以前的非NA值的fill
NA
。
library(tidyverse)
ah %>%
mutate(cor_type = replace(cor_type, str_detect(cor_type, "\\."), NA)) %>%
fill(cor_type)
# a cor_type
#1 1 soft corals
#2 2 soft corals
#3 3 soft corals
#4 4 soft corals
#5 5 soft corals
#6 6 soft corals
#7 7 sea fans
#8 8 sea fans
#9 9 sea fans
#10 10 sea fans
数据
创建了一个可重复使用的小例子。
ah <- data.frame(a = 1:10, cor_type = c("soft corals", "soft corals",
"..5", "..5", "..5","..6", "sea fans", "sea fans", "..13", "..14" ))
ah
# a cor_type
#1 1 soft corals
#2 2 soft corals
#3 3 ..5
#4 4 ..5
#5 5 ..5
#6 6 ..6
#7 7 sea fans
#8 8 sea fans
#9 9 ..13
#10 10 ..14
https://stackoverflow.com/questions/55096432
复制相似问题