使序列数字列名称前缀为字母

时间:2016-05-11 06:19:15

标签: r

我想在我的数据集中添加标签。但是,问题是我的数据集中有很多列,因此手动添加标签很费力。

我有33列,包括最后的label列,如下所示。

features <- c("f1","f2","f3","f4","f5","f6","f7","f8","f9","f10",
              "f11","f12","f13","f14","f15","f16","f17","f18","f19","f20",
              "f21","f22","f23","f24","f25","f26","f27","f28","f29","f30",
              "f31","f32","label")
colnames(urc_training_norm) <- features

正如您所看到的,手动输入每列很烦人,无法添加我想要的列名。

有没有更好的方法来生成这些名称?

3 个答案:

答案 0 :(得分:8)

您可以使用paste0命令

    > c(paste0("f", 1:32), "label")


     [1] "f1"    "f2"    "f3"    "f4"    "f5"    "f6"    "f7"    "f8"    "f9"    "f10"   "f11"   "f12"  
    [13] "f13"   "f14"   "f15"   "f16"   "f17"   "f18"   "f19"   "f20"   "f21"   "f22"   "f23"   "f24"  
    [25] "f25"   "f26"   "f27"   "f28"   "f29"   "f30"   "f31"   "f32"   "label"

这将完成工作

colnames(urc_training_norm) <- c(paste0("f", 1:32), "label")

答案 1 :(得分:7)

这是我通常的做法。 sprintf直接打印数字。通过添加%02d%03d,您可以添加前导零,这在处理大数字时很有用:D

features <- c(sprintf("f%02d", seq(1,32)),"label")
colnames(urc_training_norm) <- features

答案 2 :(得分:3)

如果您不介意使用X而不是f添加前缀,那么我们可以使用make.names()函数来设计语法上有效的名称:

make.names(c(1:4, "label"))
# [1] "X1"    "X2"    "X3"    "X4"    "label"

或者我们可以使用make.unique()

make.unique(c(rep("f", 4), "label"), sep = "")
# [1] "f"     "f1"    "f2"    "f3"    "label"