在R中使用grepl将值替换为子字符串

时间:2020-08-28 15:35:19

标签: r string data.table grepl

跟随data.table

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数字,而用Value2替换以偶数结尾的其他grepl。 我试图通过以下方式使用df$variable[grepl('250\\.[0-9]1|3|5', df$variable)] <-'Value1' df$variable[grepl('250\\.[0-9]0|2|4', df$variable)] <-'Value2' 函数。

250.

但是它将所有Value1替换为1: 1 Value2 2: 2 Value1 3: 3 Value2 4: 4 Value1 5: 5 Value1 。 如何获得这些结果的最佳方法:

base

在原始数据表中,还有更多值。 可以使用data.table处理latitude = [50.224832, 50.536422, 50.847827, 51.159044, 51.470068] longitude = [108.873007, 108.989510, 109.107829, 109.228010, 109.350097] density = [.15,.25,.35,.45,.55] output = [(latitude[i], longitude[i], density[i]) for i in range(len(latitude))] print(output) [(50.224832, 108.873007, 0.15), (50.536422, 108.98951, 0.25), (50.847827, 109.107829, 0.35), (51.159044, 109.22801, 0.45), (51.470068, 109.350097, 0.55)] 的解决方案会很棒。

3 个答案:

答案 0 :(得分:1)

原因是您的正则表达式。这是一个真正有助于了解您的正则表达式将匹配的应用程序。 https://spannbaueradam.shinyapps.io/r_regex_tester/

250\\.[0-9]1|3|5正在搜索250\\.[0-9]135,由于所有250.x都包含5,因此都是匹配项。

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

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

答案 1 :(得分:0)

使用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

答案 2 :(得分:0)

我们也可以使用

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