R colnames()将列表中的每个元素分配给第一列

时间:2013-10-18 16:46:25

标签: r columnname

我正在尝试使用列表或字符向量重命名数据框(df)中的1​​04列(我已经尝试过两种方式)。

不是将向量或列表中的104个元素分配给104列,而是将所有104个元素分配给第一列,而所有其他元素都分配给NA。

有关此行为以及如何正确执行此操作的任何建议?

> names(df)


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

> d2 = as.character(strapply(name,"(?<=[0-9]{1}=)(.{2,}?)((?= V[0-9])|(?=   $))",perl=TRUE))
> d2
[1] "c(\"ICPSR MEMBER ID NUMBER\", \"CONGRESS\", \"CHAMBER/CLASS\", \"STATE\", \"DISTRICT\", \"PARTY\", \"POL PARTY\", \"FULL NAME\", \"SEX\", \"REGION\", \"STATE BORN ..... \"ICPSR STUDY NUMBER\", \"ICPSR VERSION NUMBER\", \"ICPSR PART NUMBER\")"

 > class(d2)
 [1] "character"
 > colnames(df2) = d2
 > head(df2,1)


 c("ICPSR MEMBER ID NUMBER", "CONGRESS", "CHAMBER/CLASS", "STATE", "DISTRICT", "PARTY", "POL PARTY", "FULL NAME", "SEX", "REGION", "STATE BORN (ICPSR CODE)", "BORN/REP SAME STATE", "BORN/REP SAME REGION", "ICPSR RELATIVES CODE", "RELATIVES CLLPS", "SE ...
    1 

                                                                                                                                                                                                                                                             1
  NA NA NA NA  NA NA                        NA NA NA NA NA NA NA NA NA  NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA  NA  NA NA NA NA NA  NA  NA NA NA

1 个答案:

答案 0 :(得分:0)

创建标签矢量,然后将其分配给数据框,无需as.character

labels <- c("ICPSR MEMBER ID NUMBER", "CONGRESS")
colnames(df) <- labels