代码之家  ›  专栏  ›  技术社区  ›  Brandon Bertelsen

将colnames()赋值给数据帧的特定列

r
  •  3
  • Brandon Bertelsen  · 技术社区  · 14 年前

    colnames 基本包中的函数

    假设你有一个数据框,如下所示:

    df <- data.frame(variable = letters[1:100], value = rnorm(100))
    

    正如人们所料, colnames(df[1])

    colnames(df[1]) 
    # [1] "variable"
    

    但是,在调用特定列时,似乎不可能进行赋值

    colnames(df[1]) <- c("test")
    colnames(df[1])
    # [1] "variable"
    

    为什么?

    3 回复  |  直到 9 年前
        1
  •  4
  •   Henrik plannapus    9 年前

    您的版本没有达到预期效果的原因是 df[1] 在内存中创建一个临时数据帧,colnames函数然后更改这个临时数据帧(不是您的原始数据帧)中1列的名称,但是临时df不会做任何其他操作,因此它会被自动丢弃。你原来的数据框从未被碰过,所以下次你再碰 colnames(df[1]) 一个新的临时df将从未修改的原始df复制创建,并返回colname。

    colnames 而子集做你想做的事情,正如其他答案所示。

        2
  •  7
  •   Shane    14 年前

    因为你应该这样做:

    > colnames(df)[1] <- "test"
    > colnames(df)[1]
    [1] "test"
    

    colnames函数返回可以更改的字符向量。

        3
  •  3
  •   doug    14 年前

    打电话给 colnames() 然后 通过索引访问,该函数调用返回的1D向量的项:

    > data(Orange)    
    > Orange[1:5,]
      Tree  age circumference
    1    1  118            30
    2    1  484            58
    3    1  664            87
    4    1 1004           115
    5    1 1231           120
    > call *colnames* on the Orange dataframe and bind it to the variable *cn*
    > cn = colnames(Orange)
    > cn    
    [1] "Tree"          "age"           "circumference"
    > length(cn)
    [1] 3
    > class(cn)
     [1] "character"
    
    > # access the items of this 1D character vector by index:
    > cn[1]
    [1] "Tree"
    > cn[3]
    [1] "circumference"
    > # likewise modify any item the same way:
    > cn[3] = '2*pi*r'