Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/32.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
R 基于部分匹配替换数据帧中的值_R_Dplyr_Substitution_Startswith - Fatal编程技术网

R 基于部分匹配替换数据帧中的值

R 基于部分匹配替换数据帧中的值,r,dplyr,substitution,startswith,R,Dplyr,Substitution,Startswith,这是我的数据 > df1 col1 col2 1 0/0:6:6,0 0/0:6:6,0 2 0/0:6:6,0 0/1:6:6,0 ... 6 1/1:6:6,0 0/0:6:6,0 7 0/0:8:8,0 0/0:8:8,0 我想要的是,如果以“0/0”开头,则将“0/0:6:6,0”这样的长条目替换为0,如果以“0/1”开头,则替换为0.5,等等 到目前为止,我已经尝试过: 1) 将-u替换为 df %>% mutate(col1 = rep

这是我的数据

> df1
        col1      col2
1  0/0:6:6,0 0/0:6:6,0
2  0/0:6:6,0 0/1:6:6,0
...
6  1/1:6:6,0 0/0:6:6,0
7  0/0:8:8,0 0/0:8:8,0
我想要的是,如果以“0/0”开头,则将“0/0:6:6,0”这样的长条目替换为0,如果以“0/1”开头,则替换为0.5,等等

到目前为止,我已经尝试过:

1) 将-u替换为

df %>% mutate(col1 = replace(col1, starts_with("0/0"), 0)) %>% head()
    Error in mutate_impl(.data, dots) : 
      Evaluation error: Variable context not set.
    In addition: Warning message:
    In `[<-.factor`(`*tmp*`, list, value = 0) :
      invalid factor level, NA generated
df%>%mutate(col1=replace(col1,以(“0/0”),0开头))%>%head()
mutate_impl(.data,dots)中出错:
计算错误:未设置变量上下文。
此外:警告信息:

在“[中,我们可以使用
grepl

df1 %>%
   mutate(col1 = replace(col1, grepl("^0/0", col1), 0))
#       col1      col2
#1         0 0/0:6:6,0
#2         0 0/1:6:6,0
#3 1/1:6:6,0 0/0:6:6,0
#4         0 0/0:8:8,0
startsWith(df1$col1, "0/0")
#[1]  TRUE  TRUE FALSE  TRUE

或者使用
startsWith
from
base R

df1 %>%
    mutate(col1 = replace(col1, startsWith(col1, "0/0"), 0))

dplyr::start_with
的问题在于,它是一个辅助函数,用于根据变量的名称选择变量

df1 %>%
    select(starts_with('col1'))
#       col1
#1 0/0:6:6,0
#2 0/0:6:6,0
#6 1/1:6:6,0
#7 0/0:8:8,0
而不是变量的值,而
startsWith
逻辑
向量返回为
grepl

df1 %>%
   mutate(col1 = replace(col1, grepl("^0/0", col1), 0))
#       col1      col2
#1         0 0/0:6:6,0
#2         0 0/1:6:6,0
#3 1/1:6:6,0 0/0:6:6,0
#4         0 0/0:8:8,0
startsWith(df1$col1, "0/0")
#[1]  TRUE  TRUE FALSE  TRUE