如何删除 R 中包含特定文本的行名?

How can I delete the rownames which contain specific text in R?

我只想删除包含“Apple_”的行的行名

df <- data.frame('fruit'=c("Apple_1", "Apple_2", "Apple_3", "Pear_1", "Pear_2", "Pear_3"),
                'color'=c("Red", "Red", "Green","Green","Green","Green"))
df<- column_to_rownames(df, var="fruit")

None 这些工作因为我相信没有任何行仅称为“Apple”

row.names.remove <- c("Apple")
df[!(row.names(df) %in% row.names.remove), ]
df2<- length(which(grepl("Apple", rownames(df))))

df3<- df[row.names(df) != "Apple", , drop = FALSE]

我们可以使用 grep-

df[-grep('Apple', row.names(df)),, drop = FALSE]

invert = TRUE

df[grep('Apple', row.names(df), invert = TRUE),, drop = FALSE]

使用data.frame,行名和列名属性不能为空。一个选项是将其转换为数字索引

i1 <- grep('Apple', row.names(df))
row.names(df)[i1] <- seq_along(i1)

或转换为 matrix,然后将这些行名称更改为空白 ("")

m1 <- as.matrix(df)
row.names(m1)[i1] <- ""

as matrix 允许重复的行名,而 data.frame 则不允许。完全去掉rowname属性也是可以的,但是必须要跨越整个object