在R中创建一个包含100列所需列名的数据框

时间:2015-04-10 07:53:35

标签: r

我想创建一个包含100列的数据框,其名称为feature1,feature2,feature3 ... feature100。

我能够将数据框创建为

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

但是我的列的名字都是V1,V2等

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

然后我必须用

之类的东西来跟进
for(i in 1:100)
{
    df[,paste("feature",i,sep="")] = df[,paste("V",i,sep="")]
    df[,paste("V",i,sep="")] = NULL
}

是否有更简单的方法让我的列名称为“feature1”,“feature2”等

1 个答案:

答案 0 :(得分:3)

你可以做到

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

或在dimnames来电

中指定matrix部分
as.data.frame(matrix(0, ncol=100, nrow=2, dimnames=list(NULL, 
                 paste0('feature',1:100))))