Chapter 5 R objects exercises

For this exercise produce the following tables as data frame in R. Please carry this out in your "Exercises.R" script and remember about code sections and annotations.

Solutions are in the expandable boxes. Try your best to solve each challenge but use the solutions for help if you would like. Even if your method works it can be good to check the solution as there are many ways to do the same thing in python.

Tip: You can either write completely new code or reuse and alter previous code.

5.1 df

Note: The top row is the column names and the left-most column is the row names.

One Three Five
Two 2 6 10
Four 4 12 20
Six 6 18 30

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")

Step 2a

Create the data frame from vectors:

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

Add row names:

row.names(df) <- row_names

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)

5.2 beach_df_2

Note: The top row is the column names and the left-most column is the row names.

Crab Oystercatcher Sandpiper Starfish
Formby 10 5 1 3
West Kirby 1 6 1 3
Crosby 1 4 2 7
New Brighton 4 4 3 4

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")

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

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)