简体   繁体   English

在r中使用grep或grepl根据列的第一个字母选择列

[英]select columns based on first letter of columns using grep or grepl in r

I am attempting to use the dplyr package to select all columns that start with i.我正在尝试使用dplyr包来选择所有以 i 开头的列。 I have the following code:我有以下代码:

dat<-select(newdat1,starts_with("i"))

and the colnames for my data are:我的数据的列名是:

> colnames(newdat)
[1] "i22" "i21" "i20" "i24"

It is just a coincidence in this case they all start with i, as in other cases there will be a larger variety;在这种情况下,它们都以 i 开头只是巧合,因为在其他情况下会有更大的变化; thus, I want to automate the process.因此,我想自动化这个过程。 The issue is it appears my code using dplyr is correct;问题是我使用dplyr代码dplyr是正确的; however, I am having issues with the package, so I was wondering if/how to accomplish the same task with grep or grepl, or anything really using the base package.但是,我遇到了包问题,所以我想知道是否/如何使用 grep 或 grepl 或任何真正使用基本包的东西来完成相同的任务。 Thanks!谢谢!

With base R , you can use grep to match column names.使用基础 R ,您可以使用grep来匹配列名。 You can use您可以使用

dat<-newdat1[,grep("^i", colnames(newdat1))]

to do a starts-with like query.做一个开始类似的查询。 You can use any regular expression you want as the pattern in grep() .您可以使用任何您想要的正则表达式作为grep()的模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM