Mutate variables by specifying positions

library(tidyverse)
# toy data
df <- tibble(x = c("1500000    5kkkkk22222", "000    abcde   bb11111"))
df
#> # A tibble: 2 x 1
#>   x                     
#>   <chr>                 
#> 1 1500000    5kkkkk22222
#> 2 000    abcde   bb11111

How can create new variables from x by specifying positions?
For example, I want to create the following variables:
a: position 1
b: position 3
c: position 12
d: position 18

> df_desired 
# A tibble: 2 x 4
  a     b           c      d    
  <chr> <chr>       <chr>  <chr>
1 15    "00000    " 5kkkkk 22222
2 5k    "0    abcd" e   bb 11111

Like this?

library(dplyr)

df <- tibble(x = c("1500000    5kkkkk22222", "000    abcde   bb11111"))
df
#> # A tibble: 2 x 1
#>   x                     
#>   <chr>                 
#> 1 1500000    5kkkkk22222
#> 2 000    abcde   bb11111
df |> mutate(a=substr(x,1,2),b=substr(x,3,11),
             c=substr(x,12,17),d=substr(x,18,100)) |> 
  select(-x)
#> # A tibble: 2 x 4
#>   a     b           c      d    
#>   <chr> <chr>       <chr>  <chr>
#> 1 15    "00000    " 5kkkkk 22222
#> 2 00    "0    abcd" e   bb 11111

Created on 2022-01-30 by the reprex package (v2.0.1)

Edit with better code.

library(dplyr)
library(stringr)
df <- tibble(x = c("1500000    5kkkkk22222", "000    abcde   bb11111"))
df
df |> mutate(a=str_sub(x,1,2),b=str_sub(x,3,11),
             c=str_sub(x,12,17),d=str_sub(x,18,-1)) |> 
  select(-x)
1 Like

Many thanks! Your code is just what I wanted!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.