-1

this is the table that has the information, it is much larger but I have just included a small part of it

Part 1 : (solved) This might seem quite easy, but I am very stuck on creating code to make a graph which shows the change over time. The table shows infant mortality and I just need a graph showing how the infant mortality of one country has changed over time.

Part 2 : how can I fit a line to the data - for example, for just one country? I need to model the data as a linear response. How can I do this?


my_data <- structure(list(`1800` = c("Afghanistan", "Albania", "Algeria", 
"Andorra", "Angola", "Antigua and Barbuda", "Argentina", "Armenia", 
"Australia", "Austria"), `1801` = c(469L, 375L, 460L, NA, 486L, 
474L, 402L, 371L, 391L, 387L), `1802` = c(469L, 375L, 460L, NA, 
486L, 470L, 402L, 371L, 391L, 373L), `1803` = c(469L, 375L, 460L, 
NA, 486L, 466L, 402L, 370L, 391L, 359L), `1804` = c(469L, 375L, 
460L, NA, 486L, 462L, 402L, 370L, 391L, 346L), `1805` = c(469L, 
375L, 460L, NA, 486L, 458L, 402L, 369L, 391L, 333L), `1806` = c(469L, 
375L, 460L, NA, 486L, 455L, 402L, 369L, 391L, 321L), `1807` = c(470L, 
375L, 460L, NA, 486L, 451L, 402L, 368L, 391L, 309L), `1808` = c(470L, 
375L, 460L, NA, 486L, 447L, 402L, 368L, 391L, 325L), `1809` = c(470L, 
375L, 460L, NA, 486L, 444L, 402L, 367L, 391L, 316L)), row.names = c(NA, 
10L), class = "data.frame")

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140

2 Answers2

0

You can plot what the question asks for with package ggplot2.
This type of problems generaly has to do with reshaping the data. The format should be the long format and the data is in wide format. See this post on how to reshape the data from long to wide format.

library(dplyr)
library(tidyr)
library(ggplot2)

my_data %>% 
  rename(country = `1800`) %>%
  pivot_longer(
    cols = starts_with('18'),
    names_to = 'time',
    values_to = 'mortality'
  ) %>%
  mutate(time = as.numeric(time)) %>%
  ggplot(aes(time, mortality, color = country)) +
  geom_point() +
  geom_line()

enter image description here

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • it keeps saying that it cannot find function pivot_longer - is there a reason for this? Thanks for your help – user783029 Aug 30 '20 at 21:12
  • @000elizah000 `pivot_longer` is a new function in package `tidyr`, introduced in version `1.0.0`. See what `packageVersion('tidyr')` gives, maybe it's time to update. – Rui Barradas Aug 30 '20 at 21:27
0

We can use matplot from base R

matplot(t('row.names<-'(as.matrix(my_data[-1]), my_data[[1]])), 
          type = 'l', xaxt = 'n')
legend("top", my_data[[1]], col = seq_along(my_data[[1]]),
          fill = seq_along(my_data[[1]]))
akrun
  • 874,273
  • 37
  • 540
  • 662