【发布时间】:2021-10-08 11:00:11
【问题描述】:
我有一个包含patient_id 与患者names 匹配的数据框。
每位患者都有自己的数据文件FirstNameLastName.csv。为了匿名数据,我编写了函数read_in,它将读取每个FirstNameLastName.csv,并添加指定的patient_id。
为了进一步分析,我现在想将所有匿名数据放在一个数据框对象中。我使用 purrr 包中的 map_df() 函数尝试了此操作,但是在将 ID 与 .csv 文件中的每个读取匹配时遇到问题。有人可以帮助解决这个问题,这样结果就是一个包含所有具有受尊重 ID 的数据的数据框。
> patient_names
patient_id patient_name
1 1 Tina Turner
2 2 Michael Jackson
3 3 Michael Jordan
4 4 Dom Toretto
5 5 Lebron James
read_csv("LebronJames.csv")
Year Injury
<chr> <chr>
2020 Sprained Ankle
1990 Torn ACL
1995 Bruised Knee
2011 Sore Neck
2014 Headache
2019 Broken Leg
read_in <- function(path, patient_id= 1){
data <- read_delim(path, delim= ";",col_names = TRUE)
data <- add_column(data, patient_id= patient_names[["patient_id"]][id], .before = 1)
}
patient_id Year Injury
<int> <chr> <chr>
1 5 2020 Sprained Ankle
2 5 1990 Torn ACL
3 5 1995 Bruised Knee
4 5 2011 Sore Neck
5 5 2014 Headache
6 5 2019 Broken Leg
list.files(path= "/directory", pattern = ".csv", full.names = TRUE) %>%
map_df(read_in)
# A tibble: 1234 x 3
patient_id Year Injury
<int> <chr> <chr>
1 1 2012 Ankle
2 1 2014 Broken Arm
3 1 1999 Concussion
4 1 1987 Broken Finger
... ... ... ...
【问题讨论】:
-
当前解决方案到底有什么问题?它为您提供 3 列。您的预期输出是什么?
-
这很有效,因为我的函数的 ID 默认参数是 1。因此所有患者的 ID 都是 1。@RonakShah
标签: r string tidyverse purrr data-import