从字符串中提取值

时间:2017-06-09 15:00:16

标签: r regex

如果我有这些字符串:

df$value[1] = "3d 4H 59M"
df$value[2] = "7d 10H 46M"
df$value[3] = "12d 2H 4M"

d = days
H = Hours
M = Minutes

正如您所看到的,记录有时会给出带有2个数字的天数,带有1个数字的小时数。法线是每种类型中的1到2个数字,D,H,M。在这种情况下,如何提取每个D,H,M的值?

数据

x <- c("3d 4H 59M", "7d 10H 46M", "12d 2H 4M")

3 个答案:

答案 0 :(得分:5)

您可以使用stringr::str_match

library(stringr)

values = c("3d 4H 59M", "7d 10H 46M", "12d 2H 4M")

dhm <- str_match(values, "([0-9]{1,2})d ([0-9]{1,2})H ([0-9]{1,2})M")[,-1]
storage.mode(dhm) <- "integer"
colnames(dhm) <- c("Days", "Hours", "Minutes")

dhm
#     Days Hours Minutes
#[1,]    3     4      59
#[2,]    7    10      46
#[3,]   12     2       4

答案 1 :(得分:1)

以基地R:

v <- c("3d 4H 59M", "7d 10H 46M", "12d 2H 4M")

l <- lapply(strsplit(v, " "), function(v) as.numeric(sub("([0-9]+).*", "\\1", v)))

df <- setNames(do.call(rbind.data.frame, l), c("days","hours","minutes"))

你得到:

> df
  days hours minutes
1    3     4      59
2    7    10      46
3   12     2       4

答案 2 :(得分:0)

我们可以使用base R

更轻松地完成此操作
m1 <- matrix(scan(text=gsub("[^0-9]+", ",", x), what=numeric(),
        sep=",", quiet = TRUE), nrow =3, byrow= TRUE)[,-4]
colnames(m1) <- c("Days", "Hours", "Minutes")
m1
#     Days Hours Minutes
#[1,]    3     4      59
#[2,]    7    10      46
#[3,]   12     2       4

或另一个选项是tidyverse,首先将vector转换为data_frame,将separate转换为三列,并使用parse_number

library(tidyverse)
data_frame(x = x) %>% 
     separate(x, into = c("Days", "Hours", "Minutes")) %>% 
     mutate_all(readr::parse_number)
# A tibble: 3 x 3
#   Days Hours Minutes
#  <dbl> <dbl>   <dbl>
#1     3     4      59
#2     7    10      46
#3    12     2       4

数据

x <- c("3d 4H 59M", "7d 10H 46M", "12d 2H 4M")