Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Extract first two characters from a column in a dataframe

Tags:

r

stringr

I have a dataset with multiple and I would like to extract the first two characters from the sr column. Lastly, these characters will be stored in a new column.

Basically, I want to have a new column permit_type that has the first two character values from sr i.e. AP, SP and MP.

How can I do this?

Sample data

structure(list(date_received = c("11/30/2021  ", "11/30/2021  ", 
"11/30/2021  ", "11/30/2021  ", "11/30/2021  ", "11/17/2021  ", 
"12/3/2021  ", "12/3/2021  ", "12/13/2021  "), date_approved = c("11/30/2021", 
"11/30/2021", "11/30/2021", "11/30/2021", "11/30/2021", "11/17/2021", 
"12/3/2021", "12/3/2021", "12/3/2021"), sr = c("AP-21-080", "SP-21-081", 
"AP-21-082", "SP-21-083", "MP-21-084", "AP-21-085", "AP-21-086", 
"MP-21-087", "SP-21-088"), permit = c("AP1766856 Classroom C", 
"AP1766858 Classroom A", "AP1766862 Landscape Area", "AP1766864 Classroom B", 
"AO1766867", "06-SE-2420566", "06-E-2425187", "", "06-SM-2424110"
)), row.names = c(NA, -9L), class = c("tbl_df", "tbl", "data.frame"
))

Method 1

library(tidyverse)
df$permit_type= df%>% str_split_fixed(df$sr, "-", 2)

# Error
Error in str_split_fixed(., df$sr, "-", 2) : 
  unused argument (2)

Method 2

df$permit_type = df%>% str_extract(sr, "^.{2}")

# Error
Error in str_extract(., sr, "^.{2}") : unused argument ("^.{2}")

Method 3

df = df %>%  mutate(permit_type = str_extract_all(sr, "\\b[a-z]{2}")) 

# Returns permit_type with `Character(0)` values
like image 551
Ed_Gravy Avatar asked Nov 16 '25 23:11

Ed_Gravy


1 Answers

I just realized that actually, you can simply use substr() function to extract the first two characters. Followed the correct answer by akrun, for example,

df$permit_type<- substr(df$sr, 1, 2)

If that makes sense.

like image 110
LEE Avatar answered Nov 18 '25 13:11

LEE