Created
July 5, 2017 02:04
-
-
Save MonkmanMH/9614fda3b0c876b760c56c12cc965b2f to your computer and use it in GitHub Desktop.
column naming loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Problem: | |
# - row 2 of data file has non-data title that repeats every two columns | |
# - column 1 / row 1 header label is fine | |
# - the header in every even-numbered column applies to the next odd-humbered column (eg 2 applies to 3, 4 to 5, etc) | |
# - the header in those odd-numbered columns (3, 5, 7, etc) is read initially as an NA | |
# Solution | |
# - read column names only | |
# - hard code even and odd suffix | |
# - copy header value in those even columns to odd columns | |
# read the first row for the column names | |
col_names <- names(read_csv("datafile.csv", n_max = 0)) | |
# set the sub-names | |
sub_names <- c("EVEN", "ODD") | |
# create a vector for the new names, assign first value | |
col_name_num <- vector(mode = "character") | |
col_name_num[1] <- col_names[1] | |
# the loop | |
# -- note that in the 2nd line the first part of the column names is repeated | |
i <- 2 | |
while (i < 26) { | |
col_name_num[i] <- paste(col_names[i], ": ", sub_names[1], sep = "") | |
col_name_num[i+1] <- paste(col_names[i], ": ", sub_names[2], sep = "") | |
i <- i + 2 | |
} | |
# read the rest of the data file data, and apply the new and improved column names | |
datatable <- read_csv("datafile.csv", col_names = col_name_num, skip = 3) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment