Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/75.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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中使用grepl的值_R_String_Data.table_Grepl - Fatal编程技术网

用子字符串替换r中使用grepl的值

用子字符串替换r中使用grepl的值,r,string,data.table,grepl,R,String,Data.table,Grepl,以下是数据表 df <- data.table(id=c(1,2,3,4,5), variable=c("250.00","250.13","250.56","250.01","Value1")) 1: 1 250.00 2: 2 250.13 3: 3 250.56 4: 4 250.01 5: 5 Value1 但它将所有

以下是数据表

df <- data.table(id=c(1,2,3,4,5),
                 variable=c("250.00","250.13","250.56","250.01","Value1"))
1:  1   250.00
2:  2   250.13
3:  3   250.56
4:  4   250.01
5:  5   Value1
但它将所有
250.
替换为
Value1
。 获得这些结果的最佳方法是什么:

1:  1   Value2
2:  2   Value1
3:  3   Value2
4:  4   Value1
5:  5   Value1
在原始data.table中有更多的值。
一个带有
base
的解决方案,可以处理
数据。table
非常好。

原因是您的正则表达式。这是一个真正有助于理解你的正则表达式将匹配什么的应用程序

250\\[0-9]1 | 3 | 5
正在搜索
250\\[0-9]1
3
5
,因为所有250.x都包含5,所以它们都是匹配的

250\\\[0-9][135]
将显示以1、3或5***结尾的值。
[]
中的值被视为OR列表


***这不是100%正确,该模式将是
[135]$
,但它将匹配“Value1”,因为它以1结尾。

另一种方法是使用
stringr

library(dplyr)
library(stringr)
df %>% 
  mutate(variable = str_replace_all(variable, c("250.\\d?[13579]$" = "Value1", "250.\\d?[02468]$" = "Value2")))
#     id variable
# 1:  1   Value2
# 2:  2   Value1
# 3:  3   Value2
# 4:  4   Value1
# 5:  5   Value1
我们也可以使用

library(data.table)
df[grepl('^[0-9]', variable),  variable := 
     c("Value2", "Value1")[(as.integer(sub(".*\\.", "", variable)) %% 2)+1]]
df
#   id variable
#1:  1   Value2
#2:  2   Value1
#3:  3   Value2
#4:  4   Value1
#5:  5   Value1
library(data.table)
df[grepl('^[0-9]', variable),  variable := 
     c("Value2", "Value1")[(as.integer(sub(".*\\.", "", variable)) %% 2)+1]]
df
#   id variable
#1:  1   Value2
#2:  2   Value1
#3:  3   Value2
#4:  4   Value1
#5:  5   Value1