我有一个这样的数据框:
df <- data.frame(
v1 = sample(c("L1","L2"),5,replace = TRUE),
v2 = sample(c("F1","F3"),5,replace = TRUE),
v3 = sample(seq(1,5),5,replace = T)
)
我想(1)根据命名列表设置变量的类型:
typs <- list("v1" = "factor", "v2" = "factor", "v3" = "numeric")
(2)设置因子变量的级别:
list.levels <- list("v1" = c("L1","L2","L3"), "v2" = c("F1","F2","F3"))
理想情况下,我想使用一种通用方法,该方法可以应用于具有动态列数的数据帧。
您只需要编写自己的函数即可进行清理。这是一种可能性
fix_data <- function(data, types=NULL, flevels=NULL) {
if(!is.null(types) && length(types)>0) {
data[,names(types)] <- Map(function(col, type) {
if (type=="factor") {
factor(data[[col]])
} else if (type=="numeric") {
as.numeric(data[[col]])
} else {
stop(paste("unsupported type:", type))
}
}, names(types), types)
}
if(!is.null(flevels) && length(flevels)>0) {
data[,names(flevels)] <- Map(function(col, levels) {
factor(data[[col]], levels=levels)
}, names(flevels), flevels)
}
data
}
然后称它为fix_data(df, typs, list.levels)
。请注意,它返回一个新的data.frame,因此您可以覆盖原始数据或将其保存到新变量。
基本思想是循环遍历列表中的名称并进行正确的转换。我们Map
用来遍历列表中的名称和值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句