英文:
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 = "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?
答案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 <- 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论