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

Remove character and multiply remainder with number in R

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

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() 但这只能让我用另一个字符或 space 改变一个字符,但不允许我执行计算。我想我还需要将小数点分隔符从“,”更改为“。”能够将这些数字用作数字。

我如何在 R 中解决这个问题?

使用 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。如果没有,请告诉我们,答案可以稍作更改。

这是一个使用 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 的解决方案更容易理解。