Search code examples
rfilexlsxdata-import

Importing a file in R which has column names in first physical column


How should I import an file that has column names in the first physical column? For example, I have something like the below.

A  1  4  6
B  5  7  9
C  7  6  9

The conventional placement of this data is the following, and it is also how I want the data to look after the import.

A B C
1 5 7
4 7 6
6 9 9

It is easy to read the conventional placement, but I don't know how to read the file if the placement has the column names in a column. Can someone help?


Solution

  • You could use read.csv to read the entire file as-is, then use appropriate subsetting.

    df <- read.csv(file="input.csv")
    name_vec <- df[,1]
    df <- data.frame(t(df[,2:ncol(df)]))
    names(df) <- name_vec
    df
    
       A B C
    v2 1 5 7
    v3 4 7 6
    v4 6 9 9
    

    Data:

    df <- data.frame(v1=c("A", "B", "C"), v2=c(1,5,7), v3=c(4,7,6), v4=c(6,9,9),
        stringsAsFactors=FALSE)