How to name the unnamed first column of a data.frame

后端 未结 3 730
长发绾君心
长发绾君心 2020-12-28 20:31

I have a data frame that looks like this:

> mydf
                   val1     val2
hsa-let-7a         2.139890 -0.03477569
hsa-let-7b         2.102590  0.         


        
相关标签:
3条回答
  • 2020-12-28 20:59

    this may also work in your case,

    mydf <- cbind(rownames(mydf),mydf)
    rownames(mydf) <- NULL
    colnames(mydf) <- c(names(mydf)) #to not write all the column names
    
    colnames(mydf)[1] <- "name.of.the.first.column" 
    names(mydf)
    
    0 讨论(0)
  • 2020-12-28 21:18

    You could join the row names to the dataframe, like this:

    mydf <- cbind(rownames(mydf), mydf)
    rownames(mydf) <- NULL
    colnames(mydf) <- c("COL1","VAL1","VAL2")
    

    Or, in one step:

    setNames(cbind(rownames(mydf), mydf, row.names = NULL), 
             c("COL1", "VAL1", "VAL2"))
    #         COL1     VAL1        VAL2
    # 1 hsa-let-7a 2.139890 -0.03477569
    # 2 hsa-let-7b 2.102590  0.04108795
    # 3 hsa-let-7c 2.061705  0.02375882
    # 4 hsa-let-7d 1.938950 -0.04364545
    # 5 hsa-let-7e 1.889000 -0.10575235
    # 6 hsa-let-7f 2.264296  0.08465690
    
    0 讨论(0)
  • 2020-12-28 21:19

    If one wants to use a tidyverse solution within his/her pipeline, this works

    rownames_to_column(mydf, var = "var_name")
    

    The function is contained in the tibble package

    0 讨论(0)
提交回复
热议问题