如何使用redcapAPI包中的exportRecordsTyped函数导入无因子数据?

问题描述 投票:0回答:2

我之前使用过以下代码从 REDCap 导入数据:

data.df <- redcapAPI::exportRecords(rcon, 
                             forms = c("setup_log"),
                             labels = FALSE, 
                             factors = FALSE)

由于exportRecords函数已被弃用,我想使用redcapAPI包中的新exportRecordsTyped函数。然而,它似乎将所有字符串作为因子导入,这是我不想要的:我的代码的其余部分依赖于它们不是因子。

我一直在浏览exportRecordsTyped的帮助页面,但我还没有找到一种方法来导入所有列而不是因素。我想要类似 Factors = FALSE 的东西,它似乎不存在于新的 ExportRecordsTyped 中。有什么办法可以做到这一点吗?

我已经找到了一种使用 REDCapR 包 redcap_read_oneshot 函数来执行此操作的方法,如下所示,但我仍然想知道是否有一种方法可以使用 exportRecordsTyped 来执行此操作。

data.df <- REDCapR::redcap_read_oneshot(Redcap.url,
                                        Redcap.token,
                                        forms = c("setup_log"),
                                        verbose = FALSE
                                        )$data 

谢谢。

r import factors redcap
2个回答
1
投票

redcap API 有一个替代包:

REDCapR
。它的函数
redcap_read_oneshot()
不会将字符串转换为因子。

rc_data <- 
  redcap_read_oneshot(
  redcap_uri = "https://<url/ip to your redcap instance here>/api/",
  token = "your redcap API key here")

rc_data$data

1
投票

更新

随着版本2.8.0的发布,这可以通过使用来完成

exportRecordsTyped(rcon, 
                   cast = default_cast_no_factor)

之前的回答

一些选项:

后处理

得到你想要的最快的方法可能是

X <- exportRecordsTyped(rcon)

factor_cols <- vapply(X, is.factor, logical(1))
X[factor_cols] <- lapply(X[factor_cols], as.character)

另一种选择是使用

recastRecords

X <- exportRecordsTyped(rcon) |>
  recastRecords(rcon, 
             cast = list(dropdown = as.character, 
                         radio = as.character, 
                         checkbox = as.character, 
                         yesno = as.character))

但是如果您需要定期这样做,那么输入的内容会很多。

定义您自己的投射函数

您还可以定义一些返回字符向量而不是因子的覆盖。

castLabelCharacter <- function(x, field_name, coding){
  code_match <- getCodingIndex(x, coding)
  
  unname(coding[code_match])
}

castCheckedCharacter <- function(x, field_name, coding){
  checked_value <- getCheckedValue(coding, field_name)
  
  x_checked <- x %in% checked_value 
  
  c("Unchecked", "Checked")[(x_checked)+1]
}

然后

exportRecordsTyped(rcon, 
    cast = list(dropdown = castLabelCharacter, 
                 radio = castLabelCharacter, 
                 checkbox = castCheckedCharacter)

重新定义提供的投射功能

最后,您可以在调用之前更改转换函数的定义

exportRecordsTyped

castLabel <- function(x, field_name, coding){
  code_match <- getCodingIndex(x, coding)
  
  unname(coding[code_match])
}

castChecked <- function(x, field_name, coding){
  checked_value <- getCheckedValue(coding, field_name)
  
  x_checked <- x %in% checked_value 
  
  c("Unchecked", "Checked")[(x_checked)+1]
}

这会覆盖会话中转换函数的行为,并且需要在每次加载时运行

redcapAPI

© www.soinside.com 2019 - 2024. All rights reserved.