如果我想将名称从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等等,并将其设置为名称s /他喜欢
答案 0 :(得分:2)
通过在函数外部进行子集化替换特定的列名,而不是像第一次尝试中的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<-`
的分配。