Loss of column names in dataframe

1.4k views Asked by At

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?

1

There are 1 answers

1
Gregor Thomas On BEST ANSWER

Use drop = F to preserve the structure (not drop single-value dimensions)

test[, grepl("c1", names(test)), drop = FALSE]

E.g.:

> mtcars[1:3, "mpg"]
[1] 21.0 21.0 22.8

> mtcars[1:3, "mpg", drop = F]
               mpg
Mazda RX4     21.0
Mazda RX4 Wag 21.0
Datsun 710    22.8

For details, see ?"[".