我有35个名为PXX physiology.txt的文件,其中XX是1到35.例如。
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
要导入我通常执行的一个文件:
P1 <- read.table("P1 physiology.txt", header = FALSE, skip=14, nrow =
length(readLines("P1 physiology.txt")) - 16)
colnames(P1)<- c("Time","SkinTemp","HeartRate","RespirationRate")
我想将所有35个导入R中的某个对象,使其处于融化格式。即来自所有35个文件的所有数据都是一个在下一个文件的顶部,其中一列具有每个数据块的标签。我想融化它的原因是,我可以使用ggplot2或base来根据标签绘制它。
编辑:目前为止的代码:
我从here找到了这段代码并试图改变它但却没有成功:
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)
答案 0 :(得分:2)
# 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")