我有一个数据框,我想在其中一个列中更改一些值。
列值如下所示: [1]“软珊瑚”“软珊瑚”“软珊瑚”“软珊瑚”“软珊瑚”“软…
我不认为 case_when 是这里最好的选择。一种方法是 replace 带图案的值( \\. ) 至 NA 然后 fill NA s具有先前的非NA值。
case_when
replace
\\.
NA
fill
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