My code does not give me the expected values
| Column A | Red | Green | Blue |
|---|---|---|---|
| rgb(111,222,334) | 111 | 222 | 334 |
| rgb(11,22,3) | 11 | 22 | 3 |
Column A is divided to 3 new columns
(df_data <- df3|>
separate_wider_regex(
cols = Column A,
patterns = c(red = "rgb\\((\\d+),\\s*\\d+,\\s*\\d+\\)",
green = "rgb\\(\\d+,\\s*(\\d+),\\s*\\d+\\)",
blue = "rgb\\(\\d+,\\s*\\d+,\\s*(\\d+)\\)")
Data:
df_data <- data.frame(ColumnA = c("rgb(111,222,334)", "rgb(11,22,3)"))
>Solution :
Here is a base R solution with strsplit.
df_data <- data.frame(ColumnA = c("rgb(111,222,334)", "rgb(11,22,3)"))
strsplit(df_data$ColumnA, "[[:alpha:]]+|\\(|\\)|,") |>
lapply(\(x) {
ok <- (x |> trimws() |> nchar()) > 0L
x[ok] |> as.numeric()
}) |>
do.call(rbind.data.frame, args = _) |>
setNames(c("Red", "Green", "Blue"))
#> Red Green Blue
#> 1 111 222 334
#> 2 11 22 3
Created on 2023-11-07 with reprex v2.0.2