Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
dplyr情况:仅第一个实例受影响_R_Dplyr_Mutate - Fatal编程技术网

dplyr情况:仅第一个实例受影响

dplyr情况:仅第一个实例受影响,r,dplyr,mutate,R,Dplyr,Mutate,我有一个数据框,我想在其中一列中更改一些值 列值如下所示: [1] “软珊瑚”“软珊瑚”“软珊瑚”“软珊瑚”“软珊瑚”“软珊瑚”“软珊瑚”“软珊瑚”“软珊瑚” [8] “软珊瑚”“软珊瑚”“5”“5”“5”“5”“5”“5” [15] “.5”“5”“5”“5”“6”“6”“6” [22]“.6”…6”…6”…6”…6”…6”…6”…7” [29]“.7”…7”…7”…7”…7”…7”…7”…7” [36]“.7”…8”…8”…8”…8”…8”…8”…8” [43]“.8”“8”“8”“9”“9

我有一个数据框,我想在其中一列中更改一些值

列值如下所示:

[1] “软珊瑚”“软珊瑚”“软珊瑚”“软珊瑚”“软珊瑚”“软珊瑚”“软珊瑚”“软珊瑚”“软珊瑚” [8] “软珊瑚”“软珊瑚”“5”“5”“5”“5”“5”“5”
[15] “.5”“5”“5”“5”“6”“6”“6”
[22]“.6”…6”…6”…6”…6”…6”…6”…7”
[29]“.7”…7”…7”…7”…7”…7”…7”…7”
[36]“.7”…8”…8”…8”…8”…8”…8”…8”
[43]“.8”“8”“8”“9”“9”“9”“9”“9”
[50]“.9”“9”“9”“9”“9”“9”“10”“10”
[57]“.10”…10”…10”…10”…10”…10”…10”…10”
[64]“.11”…11”…11”…11”…11”…11”…11”…11”
[71]“.11”“11”“海扇”“海扇”“海扇”“海扇”“海扇”
[78]“海扇”“海扇”“海扇”“海扇”“13”“13”“13”
[85]“.13”…13”…13”…13”…13”…13”…13”…14”
[92]“.14”…14”…14”…14”…14”…14”…14”…14”…14”
[99]“.14”

我想用前面的值替换数字,比如“软珊瑚”或“海扇”,具体取决于位置

我的代码如下所示(ah是数据框obj,cor_type是列名):

ah%突变(cor\u n=case\u当(stringi::stri\u detect(str=cor\u type,regex=“\\”)~lag(cor\u type)时,
真~cor_型
)
)
但是,这只会更改正则表达式匹配的第一个实例,即第9行。其余的值保持不变。 我想我的假设是错误的,
mutate
是如何工作的?
PS:我不想写一个for循环

我不认为当是这里的最佳选择时,
case\u。一种方法是用模式(
\\.
)将
值替换为
NA
,然后
用以前的非NA值填充
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

ah@rangelo您想使用
stringi::stri_detect
而不是
stringr::str_detect
的任何具体原因?无。抱歉,我没有意识到该函数来自stringr软件包。没有问题
stringi
stringr
具有几乎相同的功能,但
stringr
包含在
tidyverse
中。
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