I have a vector of lists that roughly resembles the following tibble
:
library(tidyverse)
z <- tribble(
~x,
c("65", "80", "101"),
c("70", "83", "92"),
c("65", "55", "84"),
c("30", "70", "101"),
c("82", "66", "55")
)
I would like to use regex
and the tidyverse
to keep/extract only the max and min values. This is all I have so far:
z %>%
mutate(x = str_extract_all(x, "(max regex) | (min regex)"))
If we need the same type
after extraction, convert the character
vector to numeric
, extract the range
of values and reconvert it to character
while looping over the list
with map
library(dplyr)
library(purrr)
z %>%
mutate(x = map(x, ~ as.character(range(as.numeric(.x)))))
Ugly, but works:
library(tidyverse)
df <- tribble(
~x,
c(65, 80, 101),
c(70, 83, 92),
c(65, 55, 84),
c(30, 70, 101),
c(82, 66, 55)
)
df %>% mutate(row = row_number()) %>%
unchop(x) %>%
group_by(row) %>%
mutate(max = max(x),
min = min(x)) %>%
chop(x)
#> # A tibble: 5 x 4
#> # Groups: row [5]
#> row max min x
#> <int> <dbl> <dbl> <list>
#> 1 1 101 65 <dbl [3]>
#> 2 2 92 70 <dbl [3]>
#> 3 3 84 55 <dbl [3]>
#> 4 4 101 30 <dbl [3]>
#> 5 5 82 55 <dbl [3]>
Created on 2020-01-10 by the reprex package (v0.3.0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.