Is there any way to use string stored in variable as a column name in a new data frame? The expected result should be:

col.name <- 'col1'
df <- data.frame(col.name=1:4)
print(df)

# Real output
  col.name
1        1
2        2
3        3
4        4

# Expected output
  col1
1    1
2    2
3    3
4    4

I'm aware that I can create data frame and then use names() to rename column or use df[, col.name] for existing object, but I'd like to know if there is any other solution which could be used during creating data frame.

推荐答案

You cannot pass a variable into the name of an argument like that.

Instead what you can do is:

df <- data.frame(placeholder_name = 1:4)
names(df)[names(df) == "placeholder_name"] <- col.name

or use the default name of "V1":

df <- data.frame(1:4)
names(df)[names(df) == "V1"] <- col.name

or assign by position:

df <- data.frame(1:4)
names(df)[1] <- col.name

or if you only have one column just replace the entire names attribute:

df <- data.frame(1:4)
names(df) <- col.name

There's also the set_names function in the magrittr package that you can use to do this last solution in one step:

library(magrittr)
df <- set_names(data.frame(1:4), col.name)

But set_names is just an alias for:

df <- `names<-`(data.frame(1:4), col.name)

which is part of base R. Figuring out why this expression works and makes sense will be a good exercise.

R相关问答推荐

在通过最大似然估计将ODE模型与数据匹配时,为什么要匹配实际参数的转换值?

我想在R中总结一个巨大的数据框架,使我只需要唯一的lat、lon、Date(Year)和Maxium Value""""""""

将嵌套列表子集化为嵌套列表

根据日期从参考帧中创建不同的帧

Ggplot2中的重复注记

一小时满足条件的日期的 Select

以更少间隔的较小表中的聚合离散频率表

无法正确设置动态创建的Quarto标注的格式

R:从geom_ol()中删除轮廓并导出为pdf

使用for循环和粘贴创建多个变量

为什么我使用geom_density的绘图不能到达x轴?

按组和连续id计算日期差

如何在使用因子时获得Sankey图的Scale_Fill_Viridis的全范围

有毒元素与表观遗传年龄的回归模型

R-使用stri_trans_General()将其音译为德语字母

如何在R中创建这些列?

R中从因数到数字的转换

如何根据每个子框架中分类因子的唯一计数来过滤子框架列表?

如何从R调用Amazon销售合作伙伴API?

如何在甜甜圈图表中隐藏标签之外