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?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With