Home > database >  How to create a dataframe with a column name conditional on an object's value in R?
How to create a dataframe with a column name conditional on an object's value in R?

Time:01-09

I want to create a dataframe with a column whose value depends on another object's value.

Here's an example, I want my column to be called "conditional_colname":

x = "conditional_colname"
df <- data.frame(x = c(1, 2, 3))
df

>  x
1 1
2 2
3 3

I could try the following indirection syntax in tidy evaluation, but it returns an error:

data.frame({{x}} := c(1, 2, 3))
> Error in `:=`({ : could not find function ":="

I can sort out the problem through the use of the rename function and indirection in tidy evaluation syntax, as in:

df %>% rename({{x}} := x)
>   conditional_colname
1                   1
2                   2
3                   3

but that involves creating the dataframe with a wrong name and then renaming it, is there any option to do it from the creation of the dataset?

CodePudding user response:

{{..}} can be used with tibbles -

library(tibble)
library(rlang)

df <- tibble({{x}} := c(1, 2, 3))
df

# A tibble: 3 × 1
#  conditional_colname
#                <dbl>
#1                   1
#2                   2
#3                   3

A solution with data.frame would be with setNames.

df <- setNames(data.frame(c(1, 2, 3)), x)
  • Related