R for Everyone
  1. Files, Subsetting, & Tips
  2. 9  Files 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

  • 9.1 Bats solution
  • 9.2 UK retail solution

9  Files solutions

Before looking at these solutions keep in mind that there are many different ways to do the same thing in R. Therefore if your scripts are different than the ones below it does not mean they are wrong. As long as they produce the intended output they are correct.

9.1 Bats solution

Read in the file as a data frame:

bat_df <- read.csv("Chapter_8_files/bat_roosts.csv", row.names = 1, check.names = FALSE)

Add a row with column totals:

bat_df["UK",] <- colSums(bat_df) 

Add a column with row totals:

bat_df$All_Bat_Species <- rowSums(bat_df) 

Create transposed data frame:

bat_t_df <- as.data.frame(t(bat_df)) 

Write file:

write.table(bat_t_df, 
            file = "Chapter_8_files/bat_roosts_t.csv", 
            sep = ",", quote = FALSE, col.names = NA)

9.2 UK retail solution

Read in file:

uk_retail_df <- read.csv("Chapter_8_files/UK_retail.tsv", 
                         sep = "\t", row.names = 1, 
                         check.names = FALSE)

Create 2020 data frame: Read in file:

#Can index to get the desired columns
uk_retail_2020_df <- uk_retail_df[29:37,]
#Alternatively the tail() function can be used
#It is like head() but will get lowest rows
uk_retail_2020_df <- tail(uk_retail_df, n = 9)

Print food index phrases:

paste("The Food retail index for", row.names(uk_retail_2020_df),
      "was", uk_retail_2020_df$Food, 
      sep = " ")

Total and mean rows:

uk_retail_2020_df["Total",] <- colSums(uk_retail_2020_df)
uk_retail_2020_df["Average",] <- colMeans(head(uk_retail_2020_df, n = 9))

Write out file:

write.table(uk_retail_2020_df, "Chapter_8_files/UK_retail_2020.tsv", 
            sep = "\t", col.names = NA, quote = FALSE)
8  Files exercises
10  Handy tips & tricks