考慮R中的以下data.frame:
df <- data.frame(Agriculture = c(2,7,2),
Fishery = c(1,4,7),
Industry = c(5,7,3))
rownames(df) <- t(colnames(df))
如果行名是“漁業”或“工業”,我想將行值設定為 0。我可以很容易地這樣做:
df[2:3,1:3] <- 0
但是,就我而言,我有一個大 data.frame,這種方法不是最好的。相反,我想為行名匹配定義一個字符向量,如下所示:
list_of_industries <- c("Fishery", "Industry")
此后,這應該用于將 my 中的值設定為 0 df。但不知道我應該怎么做。如何在 R 中做到這一點?
uj5u.com熱心網友回復:
您可以使用which()with%in%來找出哪一行具有目標行名。
我原來的答案
df[which(rownames(df) %in% list_of_industries), ] <- 0
更新了@Ritchie Sacramento 的答案
在這個答案下的評論中,@Ritchie Sacramento 指出我們可以直接使用向量來匹配行名。
df[list_of_industries, ] <- 0
輸出
上面的兩個代碼生成相同的輸出。
Agriculture Fishery Industry
Agriculture 2 1 5
Fishery 0 0 0
Industry 0 0 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/427558.html
