Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 views
in Technique[技术] by (71.8m points)

r - Make sequential numeric column names prefixed with a letter

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...