-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyze.R
More file actions
72 lines (58 loc) · 2.58 KB
/
Copy pathanalyze.R
File metadata and controls
72 lines (58 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
## Merge the tarining and the test datasets and subset the data to have only the mean and std values
mergeData <- function() {
## Read the y data.
pathToFile <- "test/y_test.txt"
yDat <- read.table(pathToFile, header=F, col.names=c("ActivityID"))
pathToFile <- "train/y_train.txt"
yDatTrain <- read.table(pathToFile, header=F, col.names=c("ActivityID"))
pathToFile <- "test/subject_test.txt"
## Get the subject data
sDat <- read.table(pathToFile, header=F, col.names=c("SubjectID"))
pathToFile <- "train/subject_train.txt"
sDatTrain <- read.table(pathToFile, header=F, col.names=c("SubjectID"))
## Get the names of columns
colData <- read.table("features.txt", header=F, as.is=T, col.names=c("FeatureID", "FeatureName"))
## Read the X data
pathToFile <- "test/x_test.txt"
d <- read.table(pathToFile, header=F, col.names= colData$FeatureName)
pathToFile <- "train/x_train.txt"
dTrain <- read.table(pathToFile, header=F, col.names= colData$FeatureName)
reqD <- grep(".*mean\\(\\)|.*std\\(\\)", colData$FeatureName)
reqDTrain <- grep(".*mean\\(\\)|.*std\\(\\)", colData$FeatureName)
d <- d[,reqD]
dTrain <- dTrain[,reqDTrain]
## Append the activity and subject ID columns
d$ActivityID <- yDat$ActivityID
d$SubjectID <- sDat$SubjectID
dTrain$ActivityID <- yDatTrain$ActivityID
dTrain$SubjectID <- sDatTrain$SubjectID
mDat <- rbind(d, dTrain)
mDat
}
## Add the activity names as another column
addLabel <- function(data) {
labels <- read.table("activity_labels.txt", header=F, as.is=T, col.names=c("ActivityID", "ActivityName"))
labels $ActivityName <- as.factor(labels $ActivityName)
labeledData <- merge(data, labels)
labeledData
}
## Combine the two data sets and add the activity label as a column
MergeAndLabelData <- function() {
addLabel(mergeData())
}
## Data frame is already merged and labelled. Create a dataset containing the average of each variable for each activity and each subject.
processData <- function(processedData) {
library(reshape2)
## Melt data
id_vars = c("ActivityID", "ActivityName", "SubjectID")
feature_vars = setdiff(colnames(processedData), id_vars)
melted_data <- melt(processedData, id=id_vars, measure.vars= feature_vars)
## Recast
dcast(melted_data, ActivityName + SubjectID ~ variable, mean)
}
## Process the data as required, create the tidy data set and write it into a file
startProcessing <- function(file_name) {
final_data <- processData(MergeAndLabelData())
write.table(final_data, file_name)
}
startProcessing("tidyData.txt")