PSYCH 018 Index > Introduction to R: Data Frames > Solution to Exercise

Data Frames: “You Do It!” (Solution)

> # create vectors age, group, and rt
> age <- c(30, 21, 20, 35, 31, 49, 34, 32)
> group <- c('A', 'B', "B", "A", "A", "A", "B", 'B')
> rt <- c(1.34, 1.10, 0.82, 0.96, 0.76, 1.21, 1.60, 0.67)
> # create data frame stats and display it
> stats <- data.frame(age, group, rt)
> stats
  age group   rt
1  30     A 1.34
2  21     B 1.10
3  20     B 0.82
4  35     A 0.96
5  31     A 0.76
6  49     A 1.21
7  34     B 1.60
8  32     B 0.67

> # show summary of the data frame
> summary(stats)
      age        group       rt       
 Min.   :20.00   A:4   Min.   :0.670  
 1st Qu.:27.75   B:4   1st Qu.:0.805  
 Median :31.50         Median :1.030  
 Mean   :31.50         Mean   :1.058  
 3rd Qu.:34.25         3rd Qu.:1.242  
 Max.   :49.00         Max.   :1.600 
 
> # Using column numbers, show rows for the group B participants.
> stats[stats[2]=='B',]
  age group   rt
2  21     B 1.10
3  20     B 0.82
7  34     B 1.60
8  32     B 0.67

> # Using column names, show rows for reaction times < than 1 sec.
> stats[stats$rt < 1, ]
  age group   rt
3  20     B 0.82
4  35     A 0.96
5  31     A 0.76
8  32     B 0.67

> # Rows for those who are in group A AND >= 35 years old
> stats[stats$group == "A" & stats$age >= 35, ]
  age group   rt
4  35      A 0.96
6  49      A 1.21

> # Reaction times for those who are in group B OR >= 40 years old
> stats$rt[stats$group == "B" | stats$age >= 40]
[1] 1.10 0.82 1.21 1.60 0.67

Return to Data Frames