Load multiple txt files to a single data frame and retain name as a column in R

前端 未结 2 666
时光说笑
时光说笑 2021-01-28 16:24

I\'m new to R and I\'m trying to load 100 or so txt files with three columns Name, Frequency and Gender into a single data frame. The files are all name \"yob1990.txt\" etc.

2条回答
  •  逝去的感伤
    2021-01-28 17:06

    You could also use fread and rbindlist from data.table. If the files are in the working directory,

      f1 <- list.files(pattern="^yob.*\\.txt")
      f1  #created 3 files
      #[1] "yob1990.txt" "yob1991.txt" "yob1992.txt"
    
      library(data.table)
      library(stringr)
      year <- as.numeric(str_extract(f1, perl("[0-9]+(?=\\.txt)")))
      res <- rbindlist(Map(`cbind`, lapply(f1, fread), year=year))
    
      head(res)
     #    Name Frequency Gender year
     #1:   Sam        24   Male 1990
     #2:  Gobi        22   Male 1990
     #3:  Rose        44 Female 1990
     #4: Anita        35 Female 1990
     #5:  John        44   Male 1991
     #6: Sofia        52 Female 1991
    

    Or you could use unnest from tidyr

      devtools::install_github("hadley/tidyr")
      library(tidyr)
      res1 <- unnest(setNames(lapply(f1, fread), year), year)
      head(res1)
      #  year  Name Frequency Gender
      #1 1990   Sam        24   Male
      #2 1990  Gobi        22   Male
      #3 1990  Rose        44 Female
      #4 1990 Anita        35 Female
      #5 1991  John        44   Male
      #6 1991 Sofia        52 Female
    

提交回复
热议问题