![](/img/trans.png)
[英]Using lapply to apply a function over list of data frames and saving output to files with different names
[英]Saving output of lapply to respective data frames
我對 R 很陌生。這似乎是一個簡單的問題,但我只是不知道解決它的最佳方法。 我檢查了類似的問題,但沒有找到我正在尋找的答案。
我有一個數據幀列表(實際上是 tibbles),我想通過 hablar 包中的 convert() 函數來轉換數據幀中每個變量的所有數據類型。 然后我想覆蓋原始數據框。 這是一個簡化的示例數據框(注意所有變量當前都是因子)。 為簡單起見,我將 adm2 和 adm3 與 adm1 相同,但在我的真實數據中存在不同。
adm1 <- data.frame(admV1 = as.factor(c("male", "female", "male", "female")),
admV2 = as.factor(c("12.2", "13.0", "14.0", "15.1")),
admV3 = as.factor(c("free text", "more free text", "even more free text", "free text again")),
admV4 = as.factor(c("2019-01-01T12:00:00", "2019-01-01T12:00:00", "2019-01-01T12:00:00", "2019-01-01T12:00:00")))
adm1 <- as_tibble(adm1)
adm2 <- adm1
adm3 <- adm1
dis1 <- data.frame(disV1 = as.factor(c("yes", "no", "yes", "no")),
disV2 = as.factor(c("12.2", "13.0", "14.0", "15.1")),
disV3 = as.factor(c("free text", "more free text", "even more free text", "free text again")),
disV4 = as.factor(c("2019-01-01+T12:00:00", "2019-01-01+T12:00:00", "2019-01-01+T12:00:00", "2019-01-01+T12:00:00")))
dis1 <- as_tibble(dis1)
dis2 <- dis1
dis3 <- dis1
我有兩種“類型”的數據框:入院和出院。 我定義了需要轉換為每種數據類型的變量(注意,在我的實際示例中,每個變量都是一個包含多個變量名稱的字符向量):
# Define data types
adm_chr<- admV3
adm_num<- admV2
adm_fct<- admV1
adm_dte<- admV4
dis_chr<- disV3
dis_num<- disV2
dis_fct<- disV1
dis_dte<- disV4
然后我創建了一個數據集列表:
# Define datasets
adm_dfs<- list(adm1, adm2, adm2)
dis_dfs<- list(dis1, dis2, dis3)
這是我到目前為止所管理的:
# Write function
convertDataTypes<- function(dfs, type = c("adm", "dis")){
outputs1<- dfs %>% lapply(convert(chr(paste0(type, "_chr")),
num(paste0(type, "_num")),
fct(paste0(type, "_fct"))))
outputs2<- dfs %>% mutate_at(vars(paste0(type, "_dte")),
ymd_hms, tz = "GMT")
}
# Run function
convertDataTypes(adm_dfs, "adm")
我想我需要在輸出1和輸出2上使用lapply來分配變量,但可能有更好的方法來解決這個問題。 我將非常感謝您的意見。
如果 'dfs' 是data.frame
的list
,則
library(hablar)
library(purrr)
library(dplyr)
如果“類型”對應於list
每個data.frame
使用map2
convertDataTypes <- function(dfs, type = c("adm", "dis")) {
map2(dfs, type, ~ {
.type <- .y
map(.x, ~ .x %>%
convert(chr(str_c(.type, "_chr")),
num(str_c(.type, "_num")),
fct(str_c(.type, "_fct"))) %>%
mutate_at(vars(str_c(.type, "_dte")),
ymd_hms, tz = "GMT"))
})
}
dfsN <- list(adm_dfs, dis_dfs)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.