[R] How to replace a column in a data frame with another one with a different size
arun
smartpink111 at yahoo.com
Sun Jul 8 19:37:27 CEST 2012
Hi,
As the error says, the replacements should have equal number of rows.
You can either do it adding NAs,
df$V1<-c(NA,rollapply(df$V1,3,mean),NA)
df
V1
1 NA
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 NA
#or,
#use any of these
#as Michael suggested
df2<-rollapply(df,3,mean,fill=NA)
df3<-rollapply(df,3,mean,na.pad=TRUE)
identical(df2,df3)
[1] TRUE
A.K.
----- Original Message -----
From: Stathis Kamperis <ekamperi at gmail.com>
To: r-help at r-project.org
Cc:
Sent: Sunday, July 8, 2012 10:31 AM
Subject: [R] How to replace a column in a data frame with another one with a different size
Hello everyone,
I have a dataframe with 1 column and I'd like to replace that column
with a moving average.
Example:
> library('zoo')
> mydat <- seq_len(10)
> mydat
[1] 1 2 3 4 5 6 7 8 9 10
> df <- data.frame("V1" = mydat)
> df
V1
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 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,
Stathis
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
https://stat.ethz.ch/mailman/listinfo/r-help
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
mailing list