assign headers based on existing row in dataframe in R

后端 未结 5 650
谎友^
谎友^ 2020-12-12 19:31

After transforming a dataframe, I would like to assign heads/names to the columns based on an existing row. My headers are currently:

5条回答
  •  难免孤独
    2020-12-12 19:44

    Very similar to Vishnu's answer but uses the lapply to map all the data to characters then to assign them as the headers. This is really helpful if your data is imported as factors.

    DF[] <- lapply(DF, as.character)
    colnames(DF) <- DF[1, ]
    DF <- DF[-1 ,]
    

    note that that if you have a lot of numeric data or factors you want you'll need to convert them back. In this case it may make sense to store the character data frame, extract the row you want, and then apply it to the original data frame

    tempDF <- DF
    tempDF[] <- lapply(DF, as.character)
    colnames(DF) <- tempDF[1, ]
    DF <- DF[-1 ,]
    tempDF <- NULL
    

提交回复
热议问题