我有一個資料框,我試圖在其中對列進行子集化。如果我給出“未定義的列”,它應該顯示輸出
datf <- data.frame(a = c(1,2,3), b = c(4,3,4), c = c(7,6,5))
datf[c('a','b', 'v')]
Error in `[.data.frame`(datf, c("a", "b", "v")) :
undefined columns selected
預期產出
datf[c('a','b', 'v')]
a b
1 1 4
2 2 3
3 3 4
所以基本上,如果有定義的列那么很好,否則它應該排除未定義的列并執行代碼?這可能嗎?
uj5u.com熱心網友回復:
正如@zx8754 在評論中也建議的那樣,您可以intersect這樣使用:
cols <- c('a','b', 'v')
output <- datf[intersect(names(datf), cols)]
output
輸出:
a b
1 1 4
2 2 3
3 3 4
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/480407.html
標籤:r
