简体   繁体   中英

Importing data files of different lengths into R and melting them

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

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. Ie 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. 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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM