如何在R中根据对象的值创建一个带有条件列名的数据框?

huangapple go评论69阅读模式
英文:

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

问题

我想创建一个包含一个列的数据框,该列的值取决于另一个对象的值。

这里是一个示例,我想要我的列被称为“conditional_colname”:

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

>  x
1 1
2 2
3 3

我可以尝试以下 tidy evaluation中的间接语法,但会返回错误:

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

我可以通过使用 rename 函数和 tidy evaluation语法中的间接方法 来解决问题,如下所示:

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

但这涉及创建一个带有错误名称的数据框,然后重命名它,是否有从数据集创建时就完成的选项?

英文:

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 = &quot;conditional_colname&quot;
df &lt;- data.frame(x = c(1, 2, 3))
df

&gt;  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))
&gt; Error in `:=`({ : could not find function &quot;:=&quot;

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

df %&gt;% rename({{x}} := x)
&gt;   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?

答案1

得分: 4

{{..}}可以与tibbles一起使用 -

library(tibble)
library(rlang)

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

# 一个 tibble: 3 × 1
#   conditional_colname
#                <dbl>
#1                   1
#2                   2
#3                   3

使用data.frame的解决方案是使用setNames

df <- setNames(data.frame(c(1, 2, 3)), x)
英文:

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

library(tibble)
library(rlang)

df &lt;- tibble({{x}} := c(1, 2, 3))
df

# A tibble: 3 &#215; 1
#  conditional_colname
#                &lt;dbl&gt;
#1                   1
#2                   2
#3                   3

A solution with data.frame would be with setNames.

df &lt;- setNames(data.frame(c(1, 2, 3)), x)

huangapple
  • 本文由 发表于 2023年1月9日 18:36:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75056034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定