删除字符并将余数与R中的数字相乘

时间:2018-06-26 11:10:00

标签: r gsub string-substitution

我有一个简单的数据框,如下所示:

Date <- seq(as.Date("2013/1/1"), by = "day", length.out = 12)

test < -data.frame(Date)

test$Value <- c("1,4","2,3","3,6","< 1,4","2,3","3,6","1,4","2,3","3,6","< 1,4","2,3","3,6")

如果需要检测到,我需要遍历每行并删除“ <”符号。然后我需要将剩余数字乘以5。

我尝试了gsub(),但这只允许我将一个字符更改为另一个字符或空格,但不允许我执行计算。我想我还需要将小数点分隔符从“,”更改为“”。才能将这些数字用作数字。

如何在R中解决此问题?

2 个答案:

答案 0 :(得分:3)

使用sub的一种方法是匹配以下模式:

(?:<\s*)?(\d+),(\d+)

(?:<\s*)?   match a < followed by any amount of whitespace, the
            entire quantity either zero or one time
(\d+)       match and capture one or more digits before the comma
,           match the comma separator
(\d+)       match and capture one or more digits after the comma

这似乎与您的Value列中的任何条目匹配。然后,我们可以使用两个捕获组的整数和小数部分替换为基于十进制的数字。

然后,我们可以形成一个具有0/1值的乘法掩码,并为那些具有<的条目分配一个1。

mask <- grepl("<", test$Value)
test$Value <- as.numeric(sub("(?:<\\s*)?(\\d+),(\\d+)", "\\1.\\2", test$Value))
test$Value <- test$Value + (4*mask*test$Value)
test$Value

[1] 1.4 2.3 3.6 7.0 2.3 3.6 1.4 2.3 3.6 7.0 2.3 3.6

Demo

注意:我假设您想将每个 数乘以5。如果没有,请告诉我们,答案可能会略有更改。

答案 1 :(得分:1)

这是使用tidyverse

的解决方案
library(tidyverse) #load necessary packages

data <- tibble(value = c("2,3", "< 2,5", "3,5")) %>%
  mutate(value_modified = str_replace(value, ",", "\\."),  # replace the comma with a period
         value_modified = str_extract(value_modified, "[:digit:]\\.[:digit:]"), # extract the relevant characters
         value_modified = as.numeric(value_modified), # convert to numeric
         value_modified = if_else(str_detect(value, "<"), value_modified * 5, value_modified)) # multiply by five if < symbol is in the original data

我发现使用tidyverse的解决方案更易于遵循。