我有一个空数据框,这是我的模板
temp <- data.frame(matrix(ncol=3))
colnames(temp) <- c("variable", "group", "bin")
还有另一个数据框,其中包含以下细节:
info <- data.frame(group_abc = c("1", "2", "2", "3", "3", "3"), bin_abc = c("0-700", "700-750", "750-800", "800-850", "850-900", "900-950"))
我希望变量名称为“group_abc”,并将group_abc和bin的值设置为bin_abc的值。
当我尝试使用数据框中的值时,它给出了一个错误说:Error in
$ (
tmp, group, value = c("0-699", "700-750", :
replacement has 6 rows, data has 1
只需将现有数据帧的(值)分配给新名称,但只需一个简单的步骤即可更改列名称:
info <- data.frame(group_abc = c("1", "2", "2", "3", "3", "3"), bin_abc = c("0-700", "700-750", "750-800", "800-850", "850-900", "900-950"))
temp <- setNames( info, c("group", "bin"))
> temp
group bin
1 1 0-700
2 2 700-750
3 2 750-800
4 3 800-850
5 3 850-900
6 3 900-950
如果您只想要复制现有数据帧的一部分,则可以使用带有setNames调用的info
参数中的“[”选择行或列或两者。
您可以通过将临时数据帧设置为具有正确的行数以及初始化时的正确列数来解决此问题。
info <- data.frame(group_abc = c("1", "2", "2", "3", "3", "3"), bin_abc = c("0-700", "700-750", "750-800", "800-850", "850-900", "900-950"))
temp <- data.frame(matrix(ncol=3, nrow = nrow(info)))
colnames(temp) <- c("variable", "group", "bin")
temp$group <- info$group_abc
temp$bin <- info$bin_abc