[R] How to replace a column in a data frame with another one with a different size
michael.weylandt at gmail.com
Sun Jul 8 19:10:08 CEST 2012
On Jul 8, 2012, at 9:31 AM, Stathis Kamperis <ekamperi at gmail.com> wrote:
> Hello everyone,
> I have a dataframe with 1 column and I'd like to replace that column
> with a moving average.
>> mydat <- seq_len(10)
>  1 2 3 4 5 6 7 8 9 10
>> df <- data.frame("V1" = mydat)
> 1 1
> 2 2
> 3 3
> 4 4
> 5 5
> 6 6
> 7 7
> 8 8
> 9 9
> 10 10
>> df[df$V1 <- rollapply(df$V1, 3, mean)]
> Error in `$<-.data.frame`(`*tmp*`, "V1", value = c(2, 3, 4, 5, 6, 7, 8, :
> replacement has 8 rows, data has 10
I'm not sure you need the outer df[...] -- I think you just want
df$V1 <- rollapply(df$V1,3,mean)
However, this will still give you the error message you're seeing because rollapply() only returns 8 values here (you don't get the "endpoints" by default). To get the right number of rows, you want
rollapply(df$V1, 3, mean, fill = NA) # Change NA if desired
which will put NA's on each end and give you a length 10 result, as needed.
> I could use a temporary variable to store the results of rollapply()
> and then reconstruct the data frame, but I was wondering if there is a
> one-liner that can achieve the same thing.
> Best regards,
> P.S. If you don't mind, cc me at your reply because I'm not subscribed
> to the list (but I will check the archive anyway).
> R-help at r-project.org mailing list
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help