Question

Found several questions regarding changing column names in a data frame, but didn't answer the issue I have.

I am reading in a number of excel files as data frames in a loop, doing some analysis with the data for each data frame and moving the next data frame. In each data frame where I need to rename a column whose name ends with, say for example, 00010. The position of the columns change in each file/data frame.

e.g. Imported column names are: agency_id, site_no, datetime, tz_cd, 11_00010, 11_00010_cd, 12_00030,12_00030_md, ...

For my analysis, I need the following columns: site_no, datetime, 11_00010, 12_00030. I need to rename the column, 11_00010, to temperature and column, 12_00030 to salinity. If they were in the same order I can easily rename the columns using rename in plyr or colnames or names. However, the sequence or order of the columns in each data frame is not same and the columns containing 00010 and 00030 may begin with different numbers, so the position of 00010 and 00030 in the column names is not always fixed. If it were renaming would be easier. Also, I do not need the columns whose name contain 00010 or 00030 but end with cd or md etc.

Would really appreciate any way around.

Was it helpful?

Solution

Why not just use gsub?

Assuming "x" to be your column names (normally accessed via names(your-data-frame):

x <- c("agency_id", "site_no", "datetime", "tz_cd", "11_00010", 
       "11_00010_cd", "12_00030", "12_00030_md")

x <- gsub("11_00010", "temperature", x)
x <- gsub("12_00030", "salinity", x)
x
# [1] "agency_id"      "site_no"        "datetime"       "tz_cd"         
# [5] "temperature"    "temperature_cd" "salinity"       "salinity_md"

Judging by your comments, perhaps you're looking for something more like:

x <- c("agency_id", "site_no", "datetime", "tz_cd", "11_00010", 
       "11_00010_cd", "12_00030", "12_00030_md")

x[grep("_00010$", x)] <- "temperature"
x[grep("_00030$", x)] <- "salinity"
x
# [1] "agency_id"   "site_no"     "datetime"    "tz_cd"      
# [5] "temperature" "11_00010_cd" "salinity"    "12_00030_md"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top