r - 从字符中获取 cbind 中的新 data.frame 列名称

标签 r dataframe

我正在尝试从函数中由 R 自动生成的字符分配“data.frame 列名称”。我知道我可以随后使用 colnames() 更新列名称,但我觉得我应该知道如何直接执行此操作。

示例:

test <- iris[1:3, 1:2]
i <- 3
hat_char <- paste0("hat", i) 
x <- cbind(test, hat_char = 3:1)
x
  Sepal.Length Sepal.Width hat_char
1          5.1         3.5        3
2          4.9         3.0        2
3          4.7         3.2        1

期望的输出

  Sepal.Length Sepal.Width hat3
1          5.1         3.5    3
2          4.9         3.0    2
3          4.7         3.2    1

由于大量相关但不同且更基本的问题,这似乎很难搜索。

编辑: 忘了提及,但强烈推荐基础 R 解决方案。

最佳答案

使用base R中的setNames

cbind(test, setNames(list(3:1), hat_char))
#    Sepal.Length Sepal.Width hat3
#1          5.1         3.5    3
#2          4.9         3.0    2
#3          4.7         3.2    1

如果我们将其分配给同一个数据集

test[hat_char] <- 3:1

如果我们使用dplyr

library(dplyr)
test %>%
  mutate(!! hat_char := 3:1)
#    Sepal.Length Sepal.Width hat3
#1          5.1         3.5    3
#2          4.9         3.0    2
#3          4.7         3.2    1

关于r - 从字符中获取 cbind 中的新 data.frame 列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48326145/

相关文章:

r - 如何使用存储在向量中的变量名称而不使用引号?

r - 使用 purrr::map 将多个线性模型拟合到数据框中的所有观测值

r - 比较各组样本对的所有迭代(来自未配对的数据)

python - Pandas Dataframe 的 Csv 缺少列

R函数pmvnorm : Why do values and errors differ every time I run this function with the same inputs?

r - 无法编译 test.tex。有关调试提示,请参阅 https ://yihui. name/tinytex/r/#debugging。有关更多信息,请参阅 test.log。执行停止

r - 在 R 中寻找更好的方法来按字段的一部分进行分组

python - DataFrame 值以开头

python - 转换为 Pandas Dataframe 的 True/False 值

r - `sapply` 对于 "zoo"对象成功,但对于 "xts"对象则失败,为什么?