0

I got a time series with six variables which I get their leading values using the first line of the code below and removed the repeated year column with the second line. The new data has 13 columns; one for year, six variables(call it "set 1"), and six leading variables (call it "set 2").

I need to replace the columns names of set 2 with the names of set 1 with "l" at the beginning. I used str_c function from stringr package as appeared in the third column but it did not change anything.

I did test the function with another data set and it worked fine. Also checked each part of the third line and both worked fine but when trying to assign one to the other it gives nothing; no errors and no change.

s.ts<-sample %>% mutate_each(funs(lead(.,1))) %>% cbind(sample, .) # get the leading values beside the original
s.ts<-s.ts[,-8] # remove the repeted year column
colnames(s.ts[8:13])<-str_c("l", colnames(s.ts[2:7]))  # change the column names
mallet
  • 2,454
  • 3
  • 37
  • 64

1 Answers1

3

It should be

colnames(s.ts)[8:13] <- str_c( "l", colnames(s.ts)[2:7] )

The difference is, that foo[ cols ] creates a subset copy of foo. When calling

colnames( foo[ cols ] ) <- newNames

you assign the new names to this copy. It's equivalent to:

foo <- data.frame(a = 1:5, b = LETTERS[1:5], c = rnorm(5))
bar <- foo[ 1:2 ]
colnames(bar) <- c("x", "y")
foo
bar
Beasterfield
  • 7,023
  • 2
  • 38
  • 47
  • It works fine. Would you please explain the difference? Why the first one works with some sets and does not with other sets? – mallet Jul 21 '14 at 14:40
  • @AhmedSalhin see my edits, and please explain in which cases your example works. Please have also a look at http://stackoverflow.com/q/5963269/766828. – Beasterfield Jul 21 '14 at 14:58