我正在使用semTools包使用分类数据来执行全民教育。efaUnrotate()函数要求变量作为有序因子。
我正在尝试使用一个简单的代码将所有已有的因子变量转换为有序变量,不幸的是,这似乎不起作用。我想知道是否有人对此有一个解释?
我的数据:
test <- structure(list(fp_weightloss = structure(c(1L, 1L, 1L, 1L, 1L,
1L), .Label = c("0", "1"), class = "factor"), fp_gripstrength = structure(c(1L,
2L, 1L, 1L, 1L, 1L), .Label = c("0", "1"), class = "factor"),
fp_walktime = structure(c(2L, 1L, 2L, 2L, 1L, 1L), .Label = c("0",
"1"), class = "factor"), fp_metmins = structure(c(2L, 1L,
1L, 1L, 2L, 1L), .Label = c("0", "1"), class = "factor")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -6L))我的代码:
test_ord <- as.data.frame(sapply(test, as.ordered))
sapply(test_ord, class)不会导致任何更改:
fp_weightloss fp_gripstrength fp_walktime fp_metmins
"factor" "factor" "factor" "factor" 当我期望的时候:
class(as.ordered(test$fp_weightloss))
[1] "ordered" "factor" 发布于 2020-03-23 22:39:40
问题是sapply:最好完全避免它,因为它的隐式转换经常会在看不见的情况下扰乱数据,这里就是这样做的。请改用lapply:
test_ord <- as.data.frame(lapply(test, as.ordered))一般来说,我更喜欢使用vapply,因为它可以处理非list返回值,但是让vapply处理S3类似乎是不可能的。
https://stackoverflow.com/questions/60815529
复制相似问题