Importing many files at the same time and adding ID indicator

前端 未结 2 1435
盖世英雄少女心
盖世英雄少女心 2020-12-18 15:47

I have 91 files - .log format:

rajectory Log File

Rock type: 2 (0: Sphere, 1: Cuboid, 2: Rock)

Nr of Trajectories: 91
Trajectory-Mode: ON
Average Slope (D         


        
2条回答
  •  离开以前
    2020-12-18 16:32

    You could also check out purrr::map_df which behaves like lapply or for loop but returns a data.frame

    read_traj <- function(fi) {
        df <- read.table(fi, header=F, skip=23)
        df <- df[, c(1:4, 15)]
        colnames(df) <- c("t", "x", "y", "z", "Etot")
        return(df)
    }
    
    files.list <- list.files(pattern = ".log")
    library(tidyverse)
    

    map_df has a handy feature .id=... that creates a column, id, with numbers 1...N where N is number of files.

    map_df(files.list, ~read_traj(.x), .id="id")
    

    If you want to save the file name instead, use the id column to access files.list

    map_df(files.list, ~read_traj(.x), .id="id") %>%
      mutate(id = files.list[as.numeric(id)])
    

提交回复
热议问题