简体   繁体   中英

Adding column names to a .dat file in R as a new row

I am trying to work with a large Data Frame in R that was supplied to me as a .dat file. Unfortunately, the data file wasn't ideally formatted and thus I am having issues.

I can read the data file with:

myData <- read.delim(file=here("myData.dat"))

However, when I view the data frame it is using the first row of data as the headings. Due to the format of the file, I cannot edit it to add in appropriate headings directly to the file. I attempted to use:

colnames(myData) = (c("Column1", "Column2", "Column3"))

Except this replaces the data used for the column names, and hence essentially removes a row of the data set.

Attempting to use:

myData <- read.delim(file=here("myData.dat"), col.names(c("Column1", "Column2", "Column3"))

results in the error "Error in read.table(file = file, header = header, sep = sep, quote = quote, : more columns than column names".

Is there any way to add an entirely new row to use as the column names?

Side Note: The data I am working with is confidential and so I'm unable to share it. It has about 10,600 rows of data and 50 columns

The default setting for the header (column names) in read.delim is set to TRUE. Therefore the function expects column names in the first row. You can enable that argument with header = FALSE , than your colnames will be V followed by the number of each column. Futhermore you can add your own column names with the col.names argument. Just make sure your list has a name for every column in your data frame (in your case 50 names). Otherwise you may get an error.

The code might look like this:

myData <- read.delim(file=here("myData.dat"),
                     header = FALSE, 
                     col.names = c("Column1", "Column2", "Column3"))

In your case with 50 columns, I would specify the names in an own object and add the object to the read.delim function. Like this:

my.names <- c("Column1", "Column2", "Column3")

myData <- read.delim(file=here("myData.dat"),
                     header = FALSE, 
                     col.names = my.names)

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