r - 识别文件夹名称中的字符串以创建变量 (stringi r)
问题描述
我希望这能找到你。
我有一个使用与此类似的约定的 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)
}
解决方案
也许你想要类似的东西strcapture
?例如,如果您有一个像这样的文件名列表
filenames <- c(
"/path/to/SubB1V2timecourses_chanHbO_Cond2_202010281527",
"/path/to/SubB4V9timecourses_chanHbb_Cond7_202010011527"
)
然后
strcapture(
"Sub([^_]+)timecourses_chan([^_]+)_([^_]+)_\\d+",
basename(filenames),
data.frame(ID = character(), chromophore = character(), condition = character())
)
返回
ID chromophore condition
1 B1V2 HbO Cond2
2 B4V9 Hbb Cond7
将此与您的multmerge
:
multmerge <- function(mypath){
filenames <- list.files(path = mypath, full.names = TRUE) #path=mypath
metadata <- strcapture(
"Sub([^_]+)timecourses_chan([^_]+)_([^_]+)_\\d+",
basename(filenames),
data.frame(ID = character(), chromophore = character(), condition = character())
)
datalist <- lapply(seq_along(filenames), function(i, nms, info) {
df <- read.csv(file = nms[[i]], header = TRUE)
data.frame(info[i, ], df)
}, filenames, metadata)
Reduce(function(x,y) {merge(x, y, all = TRUE)}, datalist)
}
推荐阅读
- python-3.x - 当 Twilio 呼叫连接时说“你好”
- c# - 在 Visual Studio 2019 中添加新数据源失败
- symfony - Symfony 5 - 如何在课堂上获取树枝定义的路径
- firedac - FireDAC 数组 DML 和返回子句
- python - 如何为端点上的不同请求设置单独的计数器指标?
- kubernetes - Kubernetes 中的 Prometheus 有太多不健康的目标
- react-native - 函数 onLocationChange(visibleLocation,cfi) 不会为@sbrighiu/epubjs-rn 中的每个页面(flow="paginated")返回 cfi
- java - 运行“mvn clean javadoc:jar package”时出现错误“未正确定义 JAVA_HOME 环境变量”
- bpmn - 属性面板扩展中的新自定义属性未反映在 bpmn 图 xml 中
- c++ - 如何签署由 GCC 编译的 DLL 以将其发布到 Microsoft Store?