简体   繁体   中英

2 lines of headers in R from csv

I have a lot of csv files with double headers as below. (This is only part of it, and both headers contain important info) How could I combine the first two rows of the csv file to obtain a single line of header? (egLife.expectancy.at.birth..years..1Female)

  Life.expectancy.at.birth..years..1 Life.expectancy.at.birth..years..2
1                             Female                               Male
2                                 62                                 61
3                                 61                                 58
4                                 56                                 54
5                                 50                                 49
6                                 76                                 73

Read it twice and paste the headers together. For the second read limit the number of rows read since we really only need the header.

# in next 2 lines replace text=Lines with something like "myfile"
DF <- read.table(text = Lines, header = TRUE, skip = 1)
hdr1 <- read.table(text = Lines, header = TRUE, nrows = 1)
names(DF) <- paste0(names(hdr1), names(DF))

giving:

> DF
  Life.expectancy.at.birth..years..1Female Life.expectancy.at.birth..years..2Male
1                                       62                                     61
2                                       61                                     58
3                                       56                                     54
4                                       50                                     49
5                                       76                                     73

Note: We used this for the input Lines :

Lines <- "  Life.expectancy.at.birth..years..1 Life.expectancy.at.birth..years..2
                             Female                               Male
                                 62                                 61
                                 61                                 58
                                 56                                 54
                                 50                                 49
                                 76                                 73"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM