I'm working on a Shiny app. Part of the user interface involves selecting which of many columns of data to plot using drop down menus, checkboxes, etc. I am using grepl() with the user inputs to whittle down the large dataframe to the single column that winds up being plotted. Specifying this context so you know that I can't do a one-off workaround; I need a robust solution that I can apply to a thousand or more columns of data (before you scold me for having wide data, I'm doing mapping, so I'm working within the confines of a shp file) through a user interface.
It's important that I retain the name of the column being plotted for things like debugging my code, generating the graph title, etc, but in the final stage of trimming, when I get down to just one column left, the column name disappears.
If I do this:
test <- data.frame(c1 = c(1,2,3), c2 = c(4,5,6))
trimmed <- test[, grepl("c1", names(test))]
This is the return.
trimmed [1] 1 2 3
Okay, so fine. I'll force the dataframe. Trying this:
test <- data.frame(c1 = c(1,2,3), c2 = c(4,5,6))
trimmed <- as.data.frame(test[, grepl("c1", names(test))])
This is the return:
trimmed test[, grepl("c1", names(test))] 1 1 2 2 3 3
Well that column doesn't appear to be named c1 anymore.
Because of the way I'm whittling down the dataframe to a smaller subset, I don't have that column name elsewhere. In other words, I can't just rename the column in my final dataframe because I don't know in advance what that name will be.
How can I write this so that I retain the original "c1" column name?
Use
drop = F
to preserve the structure (not drop single-value dimensions)E.g.:
For details, see
?"["
.