我正在尝试从函数中由 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/