Reputation: 162
I'm wondering if I can specify some column names and let R read the rest from the header row of a CSV file. Another way to think about it would be "over-riding" some of the column names R reads.
I have files from several weather stations. Each file begins with the same columns (Station Name, Latitude, Longitude, Elevation, Date, Time), but the remaining columns have different variables depending on the station. For example, some stations measure air temperature, some measure solar radiation, some measure rainfall... etc. I want to change the headers but I don't always know what will be in the latter columns.
For a station with air temperature and humidity data, for example, I'm imagining something like:
table <- read.csv(file, col.names = c("StationName",
"Latitude",
"Longitude",
"Elevation",
"Date",
"Time"))
# as written this will throw a "header and col.names are different lengths" error...
# but is there any way to let R 'take it from here', so to speak?
# i.e., giving this:
head(table,1)
# StationName Latitude Longitude Elevation Date Time AirTemp RH
# Sagebrush Ridge 43.45 65.91 670 2017-01-01 00:00 -16.0 87.1
I can read the file in with default column names from the file headers and then change column names in a separate step but I'm curious whether it can be done at the read step.
Upvotes: 0
Views: 312
Reputation: 146224
There's not a way to do it in one step with read.csv
(or any other CSV-reading function I'm aware of).
It's trivial to do it in two steps.
Just do it in two steps.
Upvotes: 1