Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use numeric list as a variable input within gsub pattern?

Tags:

string

r

gsub

I would like to keep only the first half of every string. The imported data duplicates first names, all in a larger data frame currently:

fname: TimmyTimmy, PopPop, AdnanAdnan, KobeKobe.

First idea was to count the characters / 2, then replace that number of characters using gsub, by counting the number of characters I would like to remove from the beginning of each string, using fn_len as my variable in the pattern.

fn_len: 5, 6, 5, 4

df$fname <- 
    gsub("^[[:alpha:]]{df$fn_len}", "", df$fname)

Returns error: invalid regular expression; reason 'Invalid contents of {}'

The code works if I use a single numbers (ex. 1,2,3,4,5) but obviously not understanding some of the patterns rules here.

Alternatively, there might be a better way to do this from the start?

like image 784
panstotts Avatar asked Jul 28 '26 17:07

panstotts


1 Answers

This really seems like a substring operation would be better

fname<-c("TimmyTimmy", "PopPop", "AdnanAdnan", "KobeKobe")
substr(fname, 1, nchar(fname)/2)
# [1] "Timmy" "Pop"   "Adnan" "Kobe" 
like image 71
MrFlick Avatar answered Jul 30 '26 10:07

MrFlick