我们有以下数据框:
col1 col2 col3
ABC111001 12 12 13
ABC111002 3 4 5
ABC000111 7 6 1
ABC000112 9 23 1
如何使用“ ABC111 ”开头所有带有rownames的行,如下所示:
ABC111001 12 12 13
ABC111002 3 4 5
答案 0 :(得分:5)
给出样本数据:
data <- read.table(header=TRUE, row.names=1, sep=" ", text="x col1 col2 col3
ABC111001 12 12 13
ABC111002 3 4 5
ABC000111 7 6 1
ABC000112 9 23 1")
...您可以使用grep
选择匹配的行:
> data[grep('^ABC111', rownames(data)),]
col1 col2 col3
ABC111001 12 12 13
ABC111002 3 4 5
答案 1 :(得分:3)
您可以使用例如substr
或grepl
:
df <- read.table(header=TRUE, row.names=1, sep=" ", text="col1 col2 col3
ABC111001 12 12 13
ABC111002 3 4 5
ABC000111 7 6 1
ABC000112 9 23 1")
needle <- "ABC111"
i <- substr(row.names(df), 0, nchar(needle))==needle
i <- grepl(paste0("^", needle), row.names(df))
df[i,]
# col1 col2 col3
# ABC111001 12 12 13
# ABC111002 3 4 5