R for Everyone
  1. Foundations & Objects
  2. 6  R objects solutions
  • Start
    • 1  Introduction
  • Foundations & Objects
    • 2  Foundations of R
    • 3  Foundations of R exercises
    • 4  R objects
    • 5  R objects exercises
    • 6  R objects solutions
  • Files, Subsetting, & Tips
    • 7  Files and subsetting data
    • 8  Files exercises
    • 9  Files solutions
    • 10  Handy tips & tricks
    • 11  Handy exercises
    • 12  Handy Solutions
  • Plots
    • 13  Histograms and Line graphs
    • 14  Scatter plots and Box plot
    • 15  Plots exercises
    • 16  Plots solutions
  • Stats & Programming
    • 17  Basic stats
    • 18  Stats exercises
    • 19  Stats solutions
    • 20  Basic programming
    • 21  Student grades example
  • Appendices
    • A  Further resources

In this chapter

  • 6.1 df solution
    • 6.1.1 Step 1
    • 6.1.2 Step 2a
    • 6.1.3 Step 2b
  • 6.2 beach_df_2 solution
    • 6.2.1 Step 1
    • 6.2.2 Step 2a
    • 6.2.3 Step 2b

6  R objects solutions

6.1 df solution

6.1.1 Step 1

Create vectors for columns and row names:

One <- c(2,4,6)
Three <- c(6,12,18)
Five <- c(10,20,30)
row_names <- c("Two", "Four", "Six")

6.1.2 Step 2a

Create the data frame from vectors:

df <- data.frame(One,Three,Five)

Add row names:

row.names(df) <- row_names

6.1.3 Step 2b

Alternatively you can define the row names in the data.frame() function as an option:

df <- data.frame(One,Three,Five, row.names = row_names)

6.2 beach_df_2 solution

6.2.1 Step 1

Create vectors for columns and row names:

Crab <- c(10,1,1,4)
Oystercatcher <- c(5,6,4,4)
Sandpiper <- c(1,1,2,3)
Starfish <- c(3,3,7,4)
row_names_2 <- c("Formby","West Kirby","Crosby","New Brighton")

6.2.2 Step 2a

Create the data frame from vectors:

beach_df_2 <- data.frame(Crab,Oystercatcher,Sandpiper,Starfish)

Add row names:

row.names(beach_df_2) <- row_names_2

6.2.3 Step 2b

Alternatively you can define the row names in the data.frame() function as an option:

beach_df_2 <- data.frame(Crab,Oystercatcher,Sandpiper,Starfish, row.names = row_names_2)
5  R objects exercises
7  Files and subsetting data