After transforming a dataframe, I would like to assign heads/names to the columns based on an existing row. My headers are currently:
row.names X2 X3 X4 X5 X6 X7 X8 X9 ...
I would like to get rid of that and use the following row as column headers (without having to type them out since I have many).
The only solution I have for this is to export and re-load the data (with header=T).
colnames() function in R is used to set headers or names to columns of a dataframe or matrix. Syntax: colnames(dataframe) <- c(“col_name-1”, “col_name-2”, “col_name-3”, “col_name-4”,…..)
A data frame's rows can be accessed using rownames() method in the R programming language. We can specify the new row names using a vector of numerical or strings and assign it back to the rownames() method. The data frame is then modified reflecting the new row names.
how can make the first row 'zip, cucurrent, pacurrent...' to be the column header? A dput() of the table would help. But you can do a colnames(dat) <- as. character(dat[1,]) to set the column names and normal R syntax to "delete" the first row.
The key here is to unlist the row first.
colnames(DF) <- as.character(unlist(DF[1,])) DF = DF[-1, ]
Try this:
colnames(DF) = DF[1, ] # the first row will be the header DF = DF[-1, ] # removing the first row.
However, get a look if the data has been properly read. If you data.frame has numeric variables but the first row were characters, all the data has been read as character. To avoid this problem, it's better to save the data and read again with header=TRUE as you suggest. You can also get a look to this question: Reading a CSV file organized horizontally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With