salhin
salhin

Reputation: 2654

Add a letter to column names

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

Upvotes: 0

Views: 2210

Answers (1)

Beasterfield
Beasterfield

Reputation: 7113

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

Upvotes: 3

Related Questions