2020-10-20

How to use the first row as column names in R

Title

Problem

We want to use the first row as column names in R. In our example, we'd like to replace the original column names (V1, V2, etc.) for the first row (col1, col2, etc.).

    V1   V2   V3   V4   V5
1 col1 col2 col3 col4 col5
2 row1    2    4    5   56
3 row2   74   74    3  534
4 row3  865  768    8    7
5 row4   68   86   65   87
df <- read.table(text =  "V1    V2  V3  V4  V5
                        col1    col2    col3    col4 col5
                        row1    2   4   5   56
                        row2    74  74  3   534
                        row3    865 768 8   7
                        row4    68  86  65  87", header = TRUE )

Solution

  • Option 1
  • colnames(df) <- df[1,]
    df <- df[-1, ] 
    

  • Option 2
  • names(df) <- lapply(df[1, ], as.character)
    df <- df[-1,] 
    

    Results

      col1 col2 col3 col4 col5
    2 row1    2    4    5   56
    3 row2   74   74    3  534
    4 row3  865  768    8    7
    5 row4   68   86   65   87
    
    If we want to reset row names:

    rownames(df) <- NULL
    
      col1 col2 col3 col4 col5
    1 row1    2    4    5   56
    2 row2   74   74    3  534
    3 row3  865  768    8    7
    4 row4   68   86   65   87
    

    References

    No hay comentarios:

    Publicar un comentario

    Nube de datos