How to insert a die in the last row of the list in R?

Asked

Viewed 49 times

-1

I have a list with some data and I need to make the moving average of the last 3 data available, what I am not able to do is to include the value of this average in the last line of my list. I’ve tried using the merge, but is creating a list with two variables, as follows and would like the value to be added below the last row of the column x.

x <- c(1:20)
media <- mean(tail(x, n = 3L))
x <- merge(x,media)

x    y
1   19
2   19
3   19
4   19
5   19
6   19
7   19
8   19
9   19
10  19
11  19
12  19
13  19
14  19
15  19
16  19
17  19
18  19
19  19
20  19

1 answer

1


To make moving averages, it is best to use one of the functions roll* package zoo. In that case I’ll use rollmeanr, where the r final means that moving averages are aligned to the right. This is due to the request to be the averages of the last 3 data available.

x <- 1:20
y <- zoo::rollmeanr(x, 3, na.pad = TRUE)

Now, either of the two ways to create a table of two vectors of the same size gives the intended result. The difference is that the first gives a class object "matrix" and the second a class object "data.frame".

cbind(x, y)
data.frame(x, y)

Editing.

Reading the question better, what is asked is simply

media <- mean(tail(x, n = 3L))
x <- c(x, media)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.