I scraped this data from a json
file which feeded an interactive graphic.
df <- structure(list(x = c(\"Iraq\", \"Syria\"), Aug. = c(\"120\", \"12
These steps can help you:
colname <- names(df)
colname[2:6] <- paste(colname[2:6], "2014")
colname[7:18] <- paste(colname[7:18], "2015")
colname[19:30] <- paste(colname[19:30], "2016")
#Now set the column name in data frame
colnames(df) <- colname
# Column names after modification
#>names(df)
# [1] "x" "Aug. 2014" "Sept. 2014" "Oct. 2014" "Nov. 2014" #"Dec. 2014" "Jan. 2015" "Feb. 2015" "March 2015" "Apr. 2015"
#[11] "May 2015" "June 2015" "July 2015" "Aug. 2015" "Sept. 2015" #"Oct. 2015" "Nov. 2015" "Dec. 2015" "Jan. 2016" "Feb 2016"
#[21] "March 2016" "April 2016" "May 2016" "June 2016" "July 2016" "Aug #2016" "Sept 2016" "Oct 2016" "Nov 2016" "Dec 2016"
#[31] "Jan " "Feb " "Mar" "April " "May" #"June" "July " "Aug " "Sept " "Oct "
#[41] "Nov " "Dec" "Jan 4th"
To change the column names of a data frame, you can do this:
# Example data frame
x <- as.data.frame(
matrix(letters[1:10], nrow = 2)
);
# Change names of columns 2-5
colnames(x)[2:5] <- paste0(colnames(x)[2:5], 1:4);
# Change all column names
colnames(x) <- paste0(colnames(x), 1:5);
It may also save you a headache later if you use more standardize column names (e.g. Feb vs. Feb.). I used lubridate
here to sequence through the dates.
require(lubridate)
colnames(df)[-1] <- paste(months(seq(ymd('2014-08-01'),ymd('2018-01-01'), by = 'months'), abbreviate = T),
year(seq(ymd('2014-08-01'),ymd('2018-01-01'), by = 'months')))