簡體   English   中英

如何刪除 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")

這些都不起作用,因為我相信沒有任何行被稱為“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] <- ""

因為matrix允許重復的行名,而data.frame不允許。 也可以完全刪除 rowname 屬性,但它必須跨越整個 object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM