[英]R loops with factor creation
我想檢查我的變量中是否有少於 4 個唯一值,這是真的,我想從中創建一個因子。
我創建了一個 function:
checker <- function(x) {
if (is.numeric(x) == TRUE) {
if (length(unique(x)) < 5) {
x <- factor(x)
}
} else {
break
}
return(x)
}
但它仍然返回數字向量。
我想,出於某種原因
x <- factor(x)
不起作用,當我嘗試時:
checker <- function(x) {
x <- factor(x)
return(x)
}
循環返回數值
你可以試試這個 function
checker <- function(x) {
if (is.numeric(x) & length(unique(x)) < 5)
factor(x)
else x
}
然后使用lapply
應用它
df[] <- lapply(df, checker)
str(df)
#'data.frame': 6 obs. of 2 variables:
# $ a: Factor w/ 4 levels "1","2","3","4": 1 2 3 3 4 3
# $ b: int 1 2 3 4 5 6
或者正如@akrun 建議的dplyr
選項
library(dplyr)
df %>% mutate_if(~ is.numeric(.) && n_distinct(.) < 5, factor)
數據
df <- data.frame(a = c(1, 2, 3, 3, 4, 3), b = 1:6)
試試下面的 function:
checker <- function(x) ifelse(length(unique(x))< 5, return(factor(x)), return(x))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.