0

I have tried to look at other questions at this forum, but did not find the suitable answer for my query. That's why i am asking this question here:

I have a time series data with daily mean temperature values for 3 years 2017, 2018 and 2019 separately. For example like this:

           1.1.2017   1.1.2018   1.1.2019
Temperature     21          23        24     

Now i want to make one variable that represents daily mean temperature for 2017, 18 and 19. How should i do that in R?

I am sorry if that's a very basic question but i am really stuck at it and don't know what to do? Any help would be appreciated

hasan arshad
  • 41
  • 2
  • 6

1 Answers1

2

Assuming

  1. input is a one row data frame with Temperature being a row name as in DF shown reproducibly in the Note at the end.
  2. output is to be a two column data frame with data in first column and year in second column.

Code--

DF2 <- transform(stack(DF), ind = as.numeric(sub(".*\\.", "", ind)))
DF2
##   values  ind
## 1     21 2017
## 2     23 2018
## 3     24 2019

or if you want a zoo or ts series

library(zoo)
z <- read.zoo(DF2, index = 2)
as.ts(z)
## Time Series:
## Start = 2017 
## End = 2019 
## Frequency = 1 
## [1] 21 23 24

The code via zoo is more general since it can also handle non-consecutive years but if we knew that the years were consecutive, i.e. no missing years, then we could write this directly from DF2

with(DF2, ts(values, start = ind[1]))

Note

Lines <- "           1.1.2017   1.1.2018   1.1.2019
Temperature     21          23        24"
DF <- read.table(text = Lines, strip.white = TRUE, check.names = FALSE)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341