Imagine we have a list of variable names like following:
ls<-c("apple.mean", "orange.mean", "orange.sd", "apple.pie.mean", "orange.juice.n", "orange.juice.p%")
How can we remove the last part (after ".") in each element so we can get:
"apple" "orange" "orange" "apple.pie" "orange.juice" "orange.juice"
Note that there might be "." inside the names but I don't want those words to be split.
I was trying to use gsub("\\..*$", "",ls)
but it omits everything after the 1st dot. I'm not sure why the $ sign is not working here. Any ideas?
> gsub("\\..*$", "",ls)
[1] "apple" "orange" "orange" "apple" "orange" "orange"
You can try
sub('[.][^.]+$', '', ls)
#[1] "apple" "orange" "orange" "apple.pie" "orange.juice"
#[6] "orange.juice"
Given that this is the equivalent of removing a file extension you could use
library(tools)
file_path_sans_ext(ls)
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