Importing data files of different lengths into R and melting them

178 views Asked by At

I have 35 files named PXX physiology.txt where XX is 1 to 35. E.g.

head(P1)
  Time SkinTemp HeartRate RespirationRate
1    0   27.412        70              10
2    0   25.608        70              10
3    4   25.609        70              10
4    5   25.619        70              15
5    8   25.629        76              14
6    9   25.659        78              14

To import one file I normally do:

P1 <- read.table("P1 physiology.txt", header = FALSE, skip=14, nrow = 
                   length(readLines("P1 physiology.txt")) - 16)
colnames(P1)<- c("Time","SkinTemp","HeartRate","RespirationRate")

I'd like to import all 35 into some object in R such that it's in a melted format. I.e. all data from all 35 files is one on top of the next with a column that has a label in it for each data chunk. The reason I'd like to melt it, is so I can plot it based on label using ggplot2 or base.

Edit: Code so far:

I've found this code from here and have tried to alter it but unsuccessfully:

z <- list.files(pattern = ".*\\.txt$")
z <- lapply(1:length(z), function(x) {chars <- strsplit(z[x], "");
         cbind(data.frame(read.table(z[x])), participant = chars[[1]][1]})
z <- do.call(rbind, z)
1

There are 1 answers

15
joel.wilson On BEST ANSWER
# 1. this returns all path location of your desired files
# replace .csv with .txt or whichever ext is yours
l = list.files(path = "path_where_all files_present", pattern = ".csv", full.names = T)

# now iterate over each path, read the data , you could use(read.table instead of csv) and then add the 'id' column
# seq_along() returns indices of l
# you can add `setNames()` after reading.
library(dplyr)
l2 = bind_rows(lapply(l, read.csv), .id = "id")