对R中同一文件夹中的多个文件运行相同的分析

w8ntj3qf  于 2023-03-15  发布在  其他
关注(0)|答案(1)|浏览(94)

这里我正在分析一个文件夹中的一个文件的转换矩阵,但是我需要对同一个文件夹中的其他78个文件做同样的分析,这样我就可以得到所有人的平均流程图。

library(RcmdrMisc)
BHFF_14h31 <-read.table("BHFF_14h31.txt", header=TRUE,row.names=1, sep="\t",na.string="", dec=",")
BHFF_14h31_m <- as.matrix(BHFF_14h31)

BHFF_14h31 <- colPercents(BHFF_14h31_m, 2)
transc <- colSums(BHFF_14h31)
transr <- rowSums (BHFF_14h31)
diversity(transc, index = "shannon")

plotmat(BHFF_14h31)

数据:

dput(BHFF_14h31)
structure(list(False.feeding = c(0L, 0L, 0L, 4L, 0L, 0L, 0L, 
0L), Head.flagging = c(2L, 0L, 0L, 0L, 0L, 0L, 2L, 0L), Inverse.wing.spreading = c(0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L), Preening = c(1L, 1L, 0L, 1L, 0L, 
0L, 1L, 0L), Scratching = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), 
    Splashing = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), Tail.wagging = c(1L, 
    2L, 0L, 0L, 0L, 0L, 0L, 0L), Wing.spreading = c(0L, 0L, 0L, 
    0L, 0L, 0L, 0L, 0L)), class = "data.frame", row.names = c("False feeding", 
"Head flagging", "Inverse wing spreading", "Preening", "Scratching", 
"Splashing", "Tail wagging", "Wing spreading"))

我知道我们可以使用循环,但是我不知道怎么做。例如,数据看起来像这样:enter image description here

dgtucam1

dgtucam11#

也许这会让你有所收获

library(purrr)
list_of_files <- list.files(pattern = "*.txt", full.names = TRUE, recursive = TRUE)

  
list_names <- purrr::set_names(stringr::str_extract(list_of_files, "[^_ ]+(?=\\.txt)"))

purrr::map2_dfr(list_of_files, list_names, function(x,y){
  
  dat <- read.table(x, header=TRUE,row.names=1, sep="\t",
                    na.string="", dec=",") |> 
    as.matrix()
  
  dat_percents <- colPercents(dat, 2)
  transc <- colSums(dat_percents)
  transr <- rowSums (dat_percents)
  diversity_number <- diversity(transc, index = "shannon")
  return(data.frame(diversity = diversity_number, file_name = y))
})

相关问题