【发布时间】:2021-02-11 11:47:17
【问题描述】:
我希望这会找到你。
我有一个 csv 文件列表,这些文件使用与此类似的约定,“SubB1V2timecourses_chanHbO_Cond2_202010281527”
我想合并数据集中的所有文件并添加变量,例如 ID (B1V2)、生色团(在本例中为 HbO;但其他文件标记为 Hbb);条件(在这种情况下为 Cond2,但可能是 Cond1-Cond9)。
下面是我当前的功能。到目前为止,我可以读取 ID、时间(这是一个单独的 Excel 文档)和数据。但是,我得到了条件和发色团的 NA。我在字符串规范中缺少什么吗?
非常感谢任何帮助。
保重身体,保持健康, 卡罗琳
multmerge <- function(mypath){
require(stringi)
require(readxl)
filenames <- list.files(path=mypath, full.names=TRUE) #path=mypath
datalist <- lapply(filenames, function(x){
df <- read.csv(file=x,header= TRUE)
ID <- unlist(stri_extract_all_regex(toupper(x), "B\\d+"))
Condition <- unlist(stri_extract_all_regex(tolower(x), "Cond\\d+"))
Chromophore <- ifelse(stri_detect_regex(toupper(x), "HbO"), "HbO",
ifelse(stri_detect_regex(toupper(x), "Hbb"), "Hbb", "NA"))
#ifelse(stri_detect_regex(tolower(x), "nonsocial"),"NonSocial",
# ifelse(stri_detect_regex(tolower(x),"social-inverted"), "social_inverted",
# ifelse(stri_detect_regex(tolower(x),"social"), "social", "NA")))
# time <- read_excel("time4hz.xlsx")
df <- data.frame(ID, time, Condition, Chromophore, df)
return(df)
}) # end read-in function
Reduce(function(x,y) {merge(x,y,all = TRUE)}, datalist)
}
【问题讨论】:
-
嗨@Caroline,我认为当您使用
tolower和toupper检测字符/单词/字符串时它们是不常用的。我想他们会是Condition <- unlist(stri_extract_all_regex(x, "Cond\\d+"))、Chromophore <- ifelse(stri_detect_regex(x, "HbO"), "HbO", ifelse(stri_detect_regex(x, "Hbb"), "Hbb", "NA"))还是其他? -
感谢您的成功!
标签: r string file data-wrangling stringi