英文:
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"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论