statespace
statespace

Reputation: 1664

R: variable name to string

There are simple solutions such as:

> deparse(substitute(data))
[1] "data"

But it does not quite work when I want to extract name from a list:

> deparse(substitute(names(data)[1]))
[1] "names(data)[1]"

So the problem is that I want this as a general solution for every variable in a list/data frame/numeric that I feed into some function. And I want to see names of those variables as column names for output data frame.

Such as:

foo <- function(...) { 
   data <- list(...)
## some magic here ##
   names(output_df) <- ?? 
   output_df
}

And keep in mind that some numerics that are fed into ... don't come with names attribute. This is probably the whole reason why I want to use their environment name as column name in output data frame.

Upvotes: 2

Views: 5996

Answers (1)

statespace
statespace

Reputation: 1664

So apparently, the "??" in question above should be substituted with:

setdiff(as.character(match.call(expand.dots=TRUE)), 
        as.character(match.call(expand.dots=FALSE)))

With fully expanded example:

num_vec <- as.numeric(1:10)
list1 <- 1:10
list2 <- 11:20
list_data <- list(list1, list2)
df_data <- data.frame(list1, list2)

foo <- function(...) {
  input_list <- list(...)
  name_vec <- setdiff(as.character(match.call(expand.dots=TRUE)), 
                      as.character(match.call(expand.dots=FALSE)))
  output_df <- list()
  for(i in 1:length(input_list)) {
    output_df <- c(output_df, input_list[i])
  }
  output_df <- data.frame(output_df)
  names(output_df) <- name_vec
  output_df
}

foo(num_vec, list_data[[1]], df_data[[1]], df_data$list2)

   num_vec list_data[[1]] df_data[[1]] df_data$list2
1        1              1            1            11
2        2              2            2            12
3        3              3            3            13
4        4              4            4            14
5        5              5            5            15
6        6              6            6            16
7        7              7            7            17
8        8              8            8            18
9        9              9            9            19
10      10             10           10            20

This was my intention - get data from any sort of source, do some manipulations with it (not shown in the example as it is not related to the problem) and get a data frame as an output with column names exactly as they appear in function as variables.

Thanks to Peyton for pointing out the solution in other post which I failed to find through the search.

Upvotes: 2

Related Questions