-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun_analysis_Final.R
65 lines (61 loc) · 2.62 KB
/
run_analysis_Final.R
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
# Step1. Merges the training and the test sets to create one data set.
trainData <- read.table("train/X_train.txt")
dim(trainData) # 7352*561
trainLabel <- read.table("train/y_train.txt")
table(trainLabel)
trainSubject <- read.table("train/subject_train.txt")
testData <- read.table("test/X_test.txt")
testLabel <- read.table("test/y_test.txt")
table(testLabel)
testSubject <- read.table("test/subject_test.txt")
joinData <- rbind(trainData, testData)
dim(joinData) # 10299*561
joinLabel <- rbind(trainLabel, testLabel)
dim(joinLabel) # 10299*1
joinSubject <- rbind(trainSubject, testSubject)
dim(joinSubject) # 10299*1
# Step2. Extracts only the measurements on the mean and standard
# deviation for each measurement.
features <- read.table("features.txt")
meanStdIndices <- grep("mean\\(\\)|std\\(\\)", features[, 2])
length(meanStdIndices) # 66
joinData <- joinData[, meanStdIndices]
names(joinData) <- gsub("\\(\\)", "", features[meanStdIndices, 2]) # remove "()"
names(joinData) <- gsub("mean", "Mean", names(joinData)) # capitalize M
names(joinData) <- gsub("std", "Std", names(joinData)) # capitalize S
names(joinData) <- gsub("-", "", names(joinData)) # remove "-" in column names
# Step3. Uses descriptive activity names to name the activities in
# the data set
activity <- read.table("activity_labels.txt")
activity[, 2] <- tolower(gsub("_", "", activity[, 2]))
substr(activity[2, 2], 8, 8) <- toupper(substr(activity[2, 2], 8, 8))
substr(activity[3, 2], 8, 8) <- toupper(substr(activity[3, 2], 8, 8))
activityLabel <- activity[joinLabel[, 1], 2]
joinLabel[, 1] <- activityLabel
names(joinLabel) <- "activity"
# Step4. Appropriately labels the data set with descriptive activity
# names.
names(joinSubject) <- "subject"
cleanedData <- cbind(joinSubject, joinLabel, joinData)
write.table(cleanedData, "merged_data.txt") # write out the 1st dataset
# Step5. Creates a second, independent tidy data set with the average of
# each variable for each activity and each subject.
subjectLen <- length(table(joinSubject)) # 30
activityLen <- dim(activity)[1] # 6
columnLen <- dim(cleanedData)[2]
result <- matrix(NA, nrow=subjectLen*activityLen, ncol=columnLen)
result <- as.data.frame(result)
colnames(result) <- colnames(cleanedData)
row <- 1
for(i in 1:subjectLen) {
for(j in 1:activityLen) {
result[row, 1] <- sort(unique(joinSubject)[, 1])[i]
result[row, 2] <- activity[j, 2]
bool1 <- i == cleanedData$subject
bool2 <- activity[j, 2] == cleanedData$activity
result[row, 3:columnLen] <- colMeans(cleanedData[bool1&bool2, 3:columnLen])
row <- row + 1
}
}
head(result)
write.table(result, "data_with_means.txt") # write out the 2nd dataset