查找以特定模式结尾的名称/文本(使用基本R)。

huangapple go评论73阅读模式
英文:

find names/text that end with certain pattern (using BASE R)

问题

I'm trying to find all variables names that end with "DE".

I'm already using this "grep" to find variables that start with "TR"

names(df )[ grep( "^(TR)" , names(df) ) ]

Is there a grep way to find the end pattern.
Just an fyi, I know I can do it with "ends_with" but I'm trying to find a base r method.

names( df %>% select(ends_with( "DE" ) ) )

Thanks.

英文:

I'm trying to find all variables names that end with "DE".

I'm already using this "grep" to find variables that start with "TR"

names(df )[ grep( "^(TR)" ,  names(df) ) ]

Is there a grep way to find the end pattern.
Just an fyi, I know I can do it with "ends_with" but I'm trying to find a base r method.

names( df %>% select(ends_with( "DE" ) ) )  

Thanks.

答案1

得分: 2

base R中已经有endsWith函数

names(df)[endsWith(names(df), "DE")]
  • 一个可重现的示例
> names(iris)[endsWith(names(iris), "Length")]
[1] "Sepal.Length" "Petal.Length"

或者使用grep,使用$来指定字符串的末尾(同时,使用grep时,可以使用value = TRUE返回名称而不是数字索引)

grep("DE$", names(df), value = TRUE)
# 类似于
names(df)[grep("DE$", names(df)]

或者在base R管道中

grep("DE$", names(df)) |>
   `[`(names(df), i = _)
grep("Length", names(iris)) |>
  `[`(names(iris), i = _)
[1] "Sepal.Length" "Petal.Length"
英文:

There is already endsWith in base R

names(df)[endsWith(names(df), "DE")]

-a reproducible example

> names(iris)[endsWith(names(iris), "Length")]
[1] "Sepal.Length" "Petal.Length"

Or with grep use the $ to specify the end of the string (also, with grep, we can use value = TRUE which returns the names instead of the numeric index

grep("DE$", names(df), value = TRUE)
# similar to
names(df)[grep("DE$", names(df)]

Or in a base R pipe

grep("DE$", names(df)) |>
   `[`(names(df), i = _)
grep("Length", names(iris)) |> 
  `[`(names(iris), i = _)
[1] "Sepal.Length" "Petal.Length"

huangapple
  • 本文由 发表于 2023年2月18日 08:06:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75490292.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定