Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a data frame with 100 columns of desired column name in R

Tags:

r

I would like to create a data frame with 100 columns whose names are feature1, feature2, feature3 ... feature100.

I was able to create the data frame as

df <- as.data.frame(matrix(0, ncol = 100, nrow = 2))

But the names of my columns are all V1, V2 etc

> names(df)
  [1] "V1"   "V2"   "V3"   "V4"   "V5"   "V6"   "V7"   "V8"   "V9"   "V10"  "V11"  "V12"  "V13"  "V14"  "V15" 
 [16] "V16"  "V17"  "V18"  "V19"  "V20"  "V21"  "V22"  "V23"  "V24"  "V25"  "V26"  "V27"  "V28"  "V29"  "V30" 
 [31] "V31"  "V32"  "V33"  "V34"  "V35"  "V36"  "V37"  "V38"  "V39"  "V40"  "V41"  "V42"  "V43"  "V44"  "V45" 
 [46] "V46"  "V47"  "V48"  "V49"  "V50"  "V51"  "V52"  "V53"  "V54"  "V55"  "V56"  "V57"  "V58"  "V59"  "V60" 
 [61] "V61"  "V62"  "V63"  "V64"  "V65"  "V66"  "V67"  "V68"  "V69"  "V70"  "V71"  "V72"  "V73"  "V74"  "V75" 
 [76] "V76"  "V77"  "V78"  "V79"  "V80"  "V81"  "V82"  "V83"  "V84"  "V85"  "V86"  "V87"  "V88"  "V89"  "V90" 
 [91] "V91"  "V92"  "V93"  "V94"  "V95"  "V96"  "V97"  "V98"  "V99"  "V100"

I have to then follow that up with something like

for(i in 1:100)
{
    df[,paste("feature",i,sep="")] = df[,paste("V",i,sep="")]
    df[,paste("V",i,sep="")] = NULL
}

Is there an easier way to have my columns names as "feature1", "feature2" etc

like image 264
IAMTubby Avatar asked Sep 28 '22 08:09

IAMTubby


1 Answers

You can do

 names(df) <- paste0('feature', 1:100)

Or specify the dimnames part in the matrix call

as.data.frame(matrix(0, ncol=100, nrow=2, dimnames=list(NULL, 
                 paste0('feature',1:100))))
like image 127
akrun Avatar answered Oct 30 '22 15:10

akrun