我很抱歉提出一个非常简单的问题。我有一个数据框,我尝试将dput放在下面。
mydf <- structure(list(br.Id = c(1992.0001, 1992.0002, 1992.0003, 1992.0004,
1992.0005, 1992.0006, 1992.0007, 1992.0008, 1992.0009, 1992.001
), si.month = c(4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), br.day = c(23L,
23L, 23L, 23L, 23L, 23L, 23L, 23L, 23L, 23L), br.year = c(1992L,
1992L, 1992L, 1992L, 1992L, 1992L, 1992L, 1992L, 1992L, 1992L
), branch = 1:10, br.location = c(160170L, 160170L, 160170L, 160170L,
160170L, 160170L, 160170L, 160170L, 160170L, 160170L), si.length = c(90L,
128L, 112L, 68L, 56L, 58L, 111L, 111L, 115L, 65L), si.weight = c(9.3,
32.5, 19, 4.4, 2.1, 2.8, 16.1, 17.9, 22.7, 3.4), si.sex = structure(c(2L,
1L, 2L, 2L, 3L, 2L, 2L, 2L, 2L, 1L), .Label = c("female", "male",
"unknown"), class = "factor"), maturity = structure(c(7L, 7L,
7L, 7L, 10L, 7L, 7L, 7L, 7L, 2L), .Label = c("developing", "immature",
"mature", "nearly.ripe", "nearly.spent", "recovering", "ripe",
"running", "spent", "unknown", "yoy"), class = "factor"), age = c(NA,
NA, NA, NA, NA, NA, NA, NA, NA, 1L)), .Names = c("br.Id", "si.month",
"br.day", "br.year", "branch", "br.location", "si.length", "si.weight",
"si.sex", "maturity", "age"), row.names = c(NA, 10L), class = "data.frame")
我要做的是选择与br具有相同名称的特定列。所以输出应该看起来像
br.Id br.day br.year branch br.location
1 1992.000 23 1992 1 160170
2 1992.000 23 1992 2 160170
3 1992.000 23 1992 3 160170
4 1992.000 23 1992 4 160170
5 1992.001 23 1992 5 160170
6 1992.001 23 1992 6 160170
7 1992.001 23 1992 7 160170
8 1992.001 23 1992 8 160170
9 1992.001 23 1992 9 160170
10 1992.001 23 1992 10 160170
我想也许grep可以用来获取这些列,但我无法弄清楚如何使用它。我感谢你的帮助
答案 0 :(得分:5)
你可以使用这个吗?
一种方法是使用dplyr包。您需要加载adb push getroot /data/local/tmp
adb shell
$ cd /data/local/tmp
$ chmod 0755 getroot
$ ./getroot
。然后选择函数是用于选择变量的已知dplyr函数,然后您可以使用 contains 来获取其中包含特定字母的列。
mydf[,grep(colnames(mydf),pattern="br.",fixed = TRUE)]
答案 1 :(得分:4)
使用此
{{1}}
答案 2 :(得分:4)
或使用grepl
:
mydf[,grepl("br.",colnames(mydf))]
或使用regexpr
:
mydf[,regexpr("br.",colnames(mydf))>0]
或使用str_detect
中的stringr
:
library(stringr)
mydf[,str_detect(colnames(mydf),"br.")]
答案 3 :(得分:2)
mydf[, grep("^br.", names(mydf))]