James
James

Reputation: 1234

Why does R add an "x" when renaming raster stack layers

I have a raster stack/brick in R containing 84 layers and I am trying to name them according to year and month from 199911 to 200610 (November 1999 to October 2006). However for some reason R keeps adding an "X" onto the beginning of any names I give my layers.

Does anyone know why this is happening and how to fix it? Here are some of the ways I've tried:

# Import raster brick

rast <- brick("rast.tif")

names(rast)[1:3]

[1] "MonthlyRainfall.1" "MonthlyRainfall.2" "MonthlyRainfall.3"

## Method 1

names(rast) <- paste0(rep(1999:2006, each=12), 1:12)[11:94]
names(rast)[1:3]

[1] "X199911" "X199912" "X20001" 

## Method 2

# Create a vector of dates

dates <- format(seq(as.Date('1999/11/1'), as.Date('2006/10/1'), by='month'), '%Y%m')
dates[1:3]

[1] "199911" "199912" "200001"

# Set names

rast <- setNames(rast, dates)
names(rast)[1:3]

[1] "X199911" "X199912" "X200001"

## Method 3

names(rast) <- paste0("", dates)
names(rast)[1:3]

[1] "X199911" "X199912" "X200001"

## Method 4

substr(names(rast), 2, 7)[1:3]

[1] "199911" "199912" "200001"

names(rast) <- substr(names(rast), 2, 7)
names(rast)[1:3]

[1] "X199911" "X199912" "X200001"

To some extent I have been able to work around the problem by adding "X" to the beginning of some of my other data but now its reached the point where I can't do that any more. Any help would be greatly appreciated!

Upvotes: 4

Views: 2942

Answers (1)

ddunn801
ddunn801

Reputation: 1890

R won't allow the column to begin with a numeral so it prepends a character to avoid that restriction.

Upvotes: 5

Related Questions