如何使用redcapAPI的exportRecordsTyped函数导入非因子类型数据?
使用redcapAPI的exportRecordsTyped导入非因子类型数据
原使用已弃用的
redcapAPI::exportRecords从REDCap导入数据,代码如下:data.df <- redcapAPI::exportRecords(rcon, forms = c("setup_log"), labels = FALSE, factors = FALSE)现改用新的
exportRecordsTyped函数,但该函数默认会将所有字符串/分类变量转为因子类型,而后续代码依赖非因子数据。查阅帮助文档未找到类似factors=FALSE的参数,想了解如何用exportRecordsTyped实现非因子数据导入。目前已通过REDCapR::redcap_read_oneshot实现需求:data.df <- REDCapR::redcap_read_oneshot(Redcap.url, Redcap.token, forms = c("setup_log"), verbose = FALSE )$data
解决方法
方法1:使用categorical_as_factor参数(推荐)
exportRecordsTyped提供了categorical_as_factor参数(默认值为TRUE),专门控制是否将分类变量转换为因子类型。设置为FALSE后,分类变量会以原始的字符串或数值格式返回,完全替代原exportRecords中factors=FALSE的功能:
data.df <- redcapAPI::exportRecordsTyped( rcon, forms = c("setup_log"), labels = FALSE, categorical_as_factor = FALSE )
方法2:导入后批量转换因子为字符
如果你的redcapAPI版本未包含categorical_as_factor参数(较旧版本),可以在导入后手动将所有因子类型列转换为字符类型:
Base R实现
# 遍历数据框,仅转换因子列 data.df[] <- lapply(data.df, function(col) { if (is.factor(col)) as.character(col) else col })
dplyr实现(更简洁)
library(dplyr) data.df <- data.df %>% mutate(across(where(is.factor), as.character))
内容的提问来源于stack exchange,提问作者Shannon
相关产品推荐
相关产品推荐

