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
frombase 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