假設您有一個像這樣的data.frame:x <- data.frame(v1=1:20,v2=1:20,v3=1:20,v4=letters[1:20])您將如何只選擇x中的數字列?
3 回答

精慕HU
TA貢獻1845條經驗 獲得超8個贊
更新為避免使用不明智的sapply。
由于數據框是一個列表,因此我們可以使用list-apply函數:
nums <- unlist(lapply(x, is.numeric))
然后是標準子集
x[ , nums]
## don't use sapply, even though it's less code
## nums <- sapply(x, is.numeric)
對于更慣用的現代R,我現在建議
x[ , purrr::map_lgl(x, is.numeric)]
較少的代碼,較少的反映R的特殊問題,并且更直接,更健壯,可以在數據庫后端的小標題上使用:
dplyr::select_if(x, is.numeric)
- 3 回答
- 0 關注
- 544 瀏覽
添加回答
舉報
0/150
提交
取消