[英]check if all values in data.frame columns are integers to subset dummy variables aka are all values in a column TRUE?
我想知道是否有更簡單的方法來設置 data.frame 的整數列。
我的目標是修改 data.frame 中的數字列而不觸及純整數列(在我的情況下包含 0 或 1)。 整數列最初是因子水平變成虛擬變量,應該保持原樣。 所以我想暫時刪除它們。
為了區分數字和整數列,我使用了這里的 OP 版本( 檢查數字是否為整數)。
但是is.wholenumber
返回一個 TRUE/FALSE 矩陣,而不是像is.numeric
那樣每列一個值,因此sapply(mtcars, is.wholenumber)
對我沒有幫助。 我想出了以下解決方案,但我認為必須有更簡單的方法?
data(mtcars)
is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) abs(x - round(x)) < tol
integer_column_names <- apply(is.wholenumber(mtcars), 2, mean) == 1
numeric_df <- mtcars[, !integer_column_names]
您可以使用dplyr
以達到如這里
library(dplyr)
is_whole <- function(x) all(floor(x) == x)
df = select_if(mtcars, is_whole)
或在基礎 R
df = mtcars[ ,sapply(mtcars, is_whole)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.