I am trying to select a column on a dataframe but I need to keep its column name. Imagine it as a one column dataframe. For example, this is what I need to accomplish:
df <- data.frame(col_a = c(1,2,3), col_b = c(5,2,8))
x <- df$col_a
colnames(x)
col_a # THIS VALUE IS WHAT I NEED
If you ask R
for a colname
of a vector, it simply returns NULL
. Makes sense, but what if it was a column of a dataframe instead of a simple vector?
Why do I need this? I'm writing a function with ggplot2
and I need to specify in a lab
which column is it using to plot the results. I would rather NOT use a string text on my function to select the columns with the function if possible because it is much easier to select variables from a dataframe when iterating.
So basically function(target, values) {...
where the arguments are both these kind of "vectors/one-column-dataframes" and the input would be like my_function(target = df$col_a, values = df$col_b)
so I could get the colnames(target)
and colnames(values)
. Yes?
Any ideas? Thanks!