my df looks like this containing one column
df <- c("1:a1_01_01","2:a2_03_03","3:a3_07_07")
I want to add two more columns in this dataframe by recoding existing column like following
column1: ("1:a1", "2:a2", "3:a3")
column2:("a1","a2","a3")
CodePudding user response:
We can use trimws
library(dplyr)
df %>%
mutate(column1 =trimws(col1, whitespace = "_.*"),
column2 = trimws(column1, whitespace = "\\d :"))
data
df <- structure(list(col1 = c("1:a1_01_01", "2:a2_03_03", "3:a3_07_07"
)), class = "data.frame", row.names = c(NA, -3L))
CodePudding user response:
Here is tidyverse
approach using as_tibble
to transform to a tibble and then using separate
twice with different separator:
library(tidyverse)
as_tibble(df) %>%
separate(value, c("column1", "column2"), sep = '\\_', remove = FALSE) %>%
separate(column1, c("column0", "column2"), sep = '\\:', remove = FALSE) %>%
select(value, column1, column2)
value column1 column2
<chr> <chr> <chr>
1 1:a1_01_01 1:a1 a1
2 2:a2_03_03 2:a2 a2
3 3:a3_07_07 3:a3 a3