Set data frame column name to character string, ie switch character type to "programming language" type?

Viewed 169

I don't know how to describe this question in the title very well. As an arbitrary example, I have created a function that creates a data frame of a vector, and its argument is supposed to be the column name of the new dataframe. However, when I run the function it returns "string" as the dataframe colname, instead of "character_string" as the colname. Pretty straightforward and I know whats happening, it's just I can't seem to find the right R function to help me achieve this.

func <- function(string){
  vec <- 1:5
  df <- data.frame(string = vec)
  return(df)
}

df <- func("character_string")
df
    string
1        1
2        2
3        3
4        4
5        5

Here is another example,

func2 <- function(statement){
  df <- data.frame(col1 = 1:5, col2 = 5:10)
  flag <- FALSE
  if(statement){
    flag <- TRUE
  }
  return(flag)
}

func2("df[1,1] == 1")

This will obviously return an error, I need the func2 to return the flag as TRUE. This may seem like a very weird way of doing something, but I'm just trying to wrap my head around this concept for some other application.

1 Answers

First part of your question: You can use setNames() or names(x) <- "" to change the name of the data.frame after creation.

func <- function(string){
  vec <- 1:5
  df <- data.frame(string = vec)
  setNames(df, string)
}

func("character_string")
#>   character_string
#> 1                1
#> 2                2
#> 3                3
#> 4                4
#> 5                5

The tidyverse allows you to use the value of the function argument as a name for the variable, at the time of creation. See here for more info on that.

library(tidyverse)
func_b <- function(string){
  vec <- 1:5
  tibble({{string}} := vec)
}

func_b("character_string")
#> # A tibble: 5 x 1
#>   character_string
#>              <int>
#> 1                1
#> 2                2
#> 3                3
#> 4                4
#> 5                5

Second part of your question: A combination of eval() and parse() allows you to evaluate a condition that is supplied as a text string.

func2 <- function(statement){
  df <- data.frame(col1 = 1:5, col2 = 6:10)
  eval(parse(text = statement))
}

func2("df[1,1] == 1")
#> [1] TRUE

If you want to call a function on a comparison statement and ensure that the statement is evaluated against the function environment, meaning: you don’t put quotations around the comparison statement, use substiture() and eval() as follows.

func2_b <- function(statement){
  df <- data.frame(col1 = 1:5, col2 = 6:10)
  eval(substitute(statement))
}

func2_b(df[1,1] == 1)
#> [1] TRUE
Related