在R中的最后一个“。”之后删除字符串的最后一部分

时间:2022-03-15 20:06:18

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)但它在第一个点之后省略了所有内容。我不确定为什么$符号在这里不起作用。有任何想法吗?

> gsub("\\..*$", "",ls)
[1] "apple"  "orange" "orange" "apple"  "orange" "orange"

2 个解决方案

#1


6  

You can try

你可以试试

sub('[.][^.]+$', '', ls)
#[1] "apple"        "orange"       "orange"       "apple.pie"    "orange.juice"
#[6] "orange.juice"

#2


2  

Given that this is the equivalent of removing a file extension you could use

鉴于这相当于删除您可以使用的文件扩展名

library(tools)
file_path_sans_ext(ls)

#1


6  

You can try

你可以试试

sub('[.][^.]+$', '', ls)
#[1] "apple"        "orange"       "orange"       "apple.pie"    "orange.juice"
#[6] "orange.juice"

#2


2  

Given that this is the equivalent of removing a file extension you could use

鉴于这相当于删除您可以使用的文件扩展名

library(tools)
file_path_sans_ext(ls)