Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make sequential numeric column names prefixed with a letter

Tags:

r

I want to add a label to my dataset. However, the problems is that there are so many columns in my data sets so adding the labels manually is laborious.

I have 33 columns including the label column at the end as below.

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

As you can see, typing manually the each column is annoying to add the column names that I wanted.

Is there any better way to generate these names?

like image 925
sclee1 Avatar asked May 11 '16 06:05

sclee1


3 Answers

Here's how I usually do it. sprintf prints the numbers directly. By adding %02d or %03d you can add leading zeroes, which is helpful when dealing with large numbers :D

features <- c(sprintf("f%02d", seq(1,32)),"label")
colnames(urc_training_norm) <- features
like image 141
Buggy Avatar answered Oct 20 '22 21:10

Buggy


You can use paste0 command

    > 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"

This will do the job

colnames(urc_training_norm) <- c(paste0("f", 1:32), "label")
like image 26
Koundy Avatar answered Oct 20 '22 20:10

Koundy


If you don't mind prefixing with X instead of f, then we can use make.names() function which is designed for making syntactically valid names:

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

Or we can use make.unique():

make.unique(c(rep("f", 4), "label"), sep = "")
# [1] "f"     "f1"    "f2"    "f3"    "label"
like image 44
zx8754 Avatar answered Oct 20 '22 19:10

zx8754