Purpose: Learn to organize the original data set (date, missing value, variable creation, etc.) and then use the modified data set to analyze the data more specifically.
Case study: Analyzing the differences between male and female managers in leading their own businesses
Question: 1. Whether men and women in managerial posts differ in their degree of obedience to their superiors
2. The reason for the difference is that the gender or the country, or the age
1. Prepare the data set
1Manager <-C (1,2,3,4,5)2Date <-C ('10/24/08','10/28/08','10/1/28','10/12/08','5/1/09')3Country <-C ('US','US','UK','UK','UK')4Gender <-C ('M','F','F','M','F')5Age <-C (32,45,25,39,99)6Q1 <-C (5,3,3,3,2)7Q2 <-C (4,5,5,3,2)8Q3 <-C (5,2,5,4,1)9Q4 <-C (5,5,5,na,2)TenQ5 <-C (5,5,2,na,1) OneLeadship <-data.frame (manager,date,country,gender,age,q1,q2,q3,q4,q5.stringasfactors=f)
2. Correcting abnormal data
1 leadship <- within (leadship,{2 agecat <- NA3 ' Elder'4 'Middleage' 5 ' Young '})
# 1. Create a new variable
# 2. Bind the variable to the dataset
# 3. Filter the new variable, if age is greater than 75, the value is wrong, fill it with Na value
3. Modify the list
1 #1. Using Code modifications2Names (Leadship[6:10]) <-C ('item1','item2','Item3','ITGEM4','ITEM5')3 4 #2. Use the dialog box to modify5Fix (Leadship)
4. Data rows with Na values removed
1 newdata <-na.omit (leadship)
5. Date format Conversion
1 # 1. Formatting dates 2 # 2. Convert the field to a date type 3 ' %m-%d-%y ' 4 leadship$date <-as. Date (Leadship$date,myformat)
6. Sorting
1 # 1. Use Order (field name) to sort by default ascending, plus-is descending 2 Attach (leadship) 3 newdata <-leadship[order (gender,-age)]4 Detach (leadship)
7. Reject variables
1 # 1. Filter out the fields that need to be rejected 2 # 2. Re-assign a value to the data set after the Operation 3 myvars <-names (leadship)%in% c ('Q3','Q4 ' )4 newdata <-Leadship[!myvars]
8. Conditional filtering
1 # 1. Select all rows with age greater than or equal to 35 or less than 24, and leave the variable q1~q4 2 # 2. Select all males over the age of 25 and keep all columns of gender to Q4 3 newdata <-subset (leadship,age>=35 | Age < 24,select = C (q1,q2,q3,q4))45 NewData <-subset (leadship,gender='M' & age > 25,select = gender:q4)
9. Random Sampling
1 # randomly extracting 3 rows of data from a data set 2 mysample <-leadship[sample (1:nrow (leadship), 3,replace = F),]
10. Working with SQL data sets
<-sqldf ('select * from Mtcars where carb=1 order by mpg', row.names = T) sqldf ( 'Select AVG (MPG) as AVG_MPG,AVG (disp) as avg_disp,gear from Mtcars where Cyl in (4,6) group BY Gear' )
Case 2: A group of students took the exam in science, mathematics, and English, in order to measure the level of the students ' uniform examination, the first 20% students were a, the next 20% students were B, and so on, and then the students were sorted by alphabet.
1. Preparing the data
1Options (digits = 2)2Student <-C ('John Davis','Angela Williams','Bullwinkle Moose','David Jones',3 'Janice Markhammer','Cheryl Cushing','Reuven Ytzrhak','Greg Knox',4 'Joel England','Mary Rayburn')5Math <-C (502,600,412,358,495,512,410,625,573,522)6Science <-C (95,99,80,82,75,85,80,95,89,86)7中文版 <-C (25,22,18,15,20,28,15,30,27,18)8Roster <-Data.frame (student,math,science,english,stringsasfactors = F)
2. Conversion of exam Results
# due to inconsistent scores for each course, the standard deviation is calculated for all results to standardize z <-scale (Roster[,2:4])
3. Calculate the average of the standard deviation of a grade
# 1. Calculate the average of each row by mean # 2. Add to DataSet using Cbind score <-apply (z, 1<-cbind (Roster,score)
4. Grading (A,B,C,D,F)
1 y <-quantile (score,c (. 8,.6,.4,.2))
5. Create a new variable level based on the percentile operator
1Roster$grade[score >= Y[1]] <-'A'2Roster$grade[score < y[1] & score >= y[2]] <-'B'3Roster$grade[score < y[2] & score >= y[3]] <-'C'4Roster$grade[score < y[3] & score >= Y[4]] <-'D'5Roster$grade[score < y[4]] <-'F'
6. Split the student's name into FirstName and LastName
# 1. Split the variable as a space # 2. Get the second element is LastName, the first element is FirstName # 3. Combine the two items into a dataset and discard the original name <-strsplit (roster$student)," [', 2'[', 1<-cbind (firstname,lastname , Roster[,-1])
7. Sort by FirstName and LastName
Roster <-Roster[order (Firstname,lastname),]
8. Using a custom function (to achieve descriptive statistics calculation)
1Mystats <-function (x,parametric=t,Print=F) {2 if(parametric) {3Center <-mean (x); spread <-SD (x)4 }5 Else{6Center <-median (x); spread <-Max (x)7 }8 if(Print¶metric) {9Cat'mean=', center,'\ n','sd=', Spread,'\ n')Ten } One Else if(Print&!parametric) { ACat'median=', center,'\ n','mad=', Spread,'\ n') - } -Result <-List (center=center,spread=spread) the return(Result) -}
1 # 1. Generate a random sample of 500 that is subject to normal distribution 2 # 2. Execute statements to get the values of Y$center and Y$spread 3 set.seed (1234)4 x <-rnorm (5) y <-mystats (x)
# 1. Or get the median and mad values y <-mystats (x,parametric = F,print = T)
Implementation of 9.switch statements
1MyDate <-Function (type='Long'){2 switch (type,3Long = Format (Sys.time (),'%A%B%d%Y'),4Short = Format (Sys.time (),'%m-%d-%y'),5Cat (Type,'is not a recognized type\n')6 )7 }8 9 #1. Default invocation of a parameter of type longTen #2. If short is called, the short format One #3. Otherwise output error message AMyDate ('Long') -MyDate (' Short')
10. Consolidating data
1 # using aggregate to consolidate data, the first parameter is a dataset, the second parameter is the column to be consolidated, and the third parameter is what function to use for row data processing 2 options (digits = 3)3Attach (mtcars)4'mean' , na.rm=T)5aggdata6 Detach (Mtcars)
R language-Basic data management