gpt4 book ai didi

r - 更改数据框中某些列的名称

转载 作者:行者123 更新时间:2023-12-02 01:28:21 32 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Changing column names of a data frame

(18 个回答)


6年前关闭。




如果我想将名称从 2 列更改为末尾,为什么我的命令不起作用?

fredTable <- structure(list(Symbol = structure(c(3L, 1L, 4L, 2L, 5L), .Label = c("CASACBM027SBOG", 
"FRPACBW027SBOG", "TLAACBM027SBOG", "TOTBKCR", "USNIM"), class = "factor"),
Name = structure(1:5, .Label = c("bankAssets", "bankCash",
"bankCredWk", "bankFFRRPWk", "bankIntMargQtr"), class = "factor"),
Category = structure(c(1L, 1L, 1L, 1L, 1L), .Label = "Banks", class = "factor"),
Country = structure(c(1L, 1L, 1L, 1L, 1L), .Label = "USA", class = "factor"),
Lead = structure(c(1L, 1L, 3L, 3L, 2L), .Label = c("Monthly",
"Quarterly", "Weekly"), class = "factor"), Freq = structure(c(2L,
1L, 3L, 3L, 4L), .Label = c("1947-01-01", "1973-01-01", "1973-01-03",
"1984-01-01"), class = "factor"), Start = structure(c(1L,
1L, 1L, 1L, 1L), .Label = "Current", class = "factor"), End = c(TRUE,
TRUE, TRUE, TRUE, FALSE), SeasAdj = c(FALSE, FALSE, FALSE,
FALSE, TRUE), Percent = structure(c(1L, 1L, 1L, 1L, 1L), .Label = "Fed", class = "factor"),
Source = structure(c(1L, 1L, 1L, 1L, 1L), .Label = "Res", class = "factor"),
Series = structure(c(1L, 1L, 1L, 1L, 2L), .Label = c("Level",
"Ratio"), class = "factor")), .Names = c("Symbol", "Name",
"Category", "Country", "Lead", "Freq", "Start", "End", "SeasAdj",
"Percent", "Source", "Series"), row.names = c("1", "2", "3",
"4", "5"), class = "data.frame")

然后为了将第二列名称更改为末尾,我使用以下命令但不起作用
names(fredTable[,-1]) = paste("case", 1:ncol(fredTable[,-1]), sep = "")

或者
names(fredTable)[,-1] = paste("case", 1:ncol(fredTable)[,-1], sep = "")

一般来说,如何更改特定列的列名,例如
2 到结尾,2 到 7 等等,并将其设置为他/她喜欢的名字

最佳答案

通过在函数外部而不是 names 内设置子集来替换特定列名与您的第一次尝试一样:

> names(fredTable)[-1] <- paste("case", 1:ncol(fredTable[,-1]), sep = "")

解释

如果我们将新名称保存在向量中 newnames我们可以通过替换函数来调查幕后发生的事情。
#These are the names that will replace the old names
newnames <- paste("case", 1:ncol(fredTable[,-1]), sep = "")

我们应该始终用以下格式替换特定的列名:
#The right way to replace the second name only
names(df)[2] <- "newvalue"

#The wrong way
names(df[2]) <- "newvalue"

问题是您正在尝试创建一个新的列名向量,然后将输出分配给数据框。这两个操作在正确的替换中同时完成。

正道【内部】

我们可以扩展函数调用:
#We enter this:
names(fredTable)[-1] <- newnames

#This is carried out on the inside
`names<-`(fredTable, `[<-`(names(fredTable), -1, newnames))

错误的方式[内部]

换错方式的内部是这样的:
#Wrong way
names(fredTable[-1]) <- newnames

#Wrong way Internal
`names<-`(fredTable[-1], newnames)

注意没有 `[<-`任务。子集数据框 fredTable[-1]在全局环境中不存在,所以没有为 `names<-` 赋值发生。

关于r - 更改数据框中某些列的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35632864/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com