I have a dirty dataset that I could not read it with header = T
. After I read and clean it, I would like to use the now first row data as the column name. I tried multiple methods on Stack Overflow without success. What could be the problem?
The dataset t1
should look like this after clean up:
V1 V2 V3 V4 V5 1 col1 col2 col3 col4 2 row1 2 4 5 56 3 row2 74 74 3 534 4 row3 865 768 8 7 5 row4 68 86 65 87
I tried: colnames(t1) <- t1[1,]
. Nothing happens.
I tried: names(t1) <- ti[1,]
, Nothing happens.
I tried: lapply(t1, function(x) {names(x) <- x[1, ]; x})
. It returns an error message:
Error in `[.default`(x, 1, ) : incorrect number of dimensions
Could anyone help?
The rownames() method in R is used to assign row names to the dataframe. It is assigned using a character vector consisting of desired names with a length equivalent to the number of rows in dataframe. We can simply assign it to any column of the dataframe if it contains all unique values.
Method 1: using colnames() method colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector. The new name replaces the corresponding old name of the column in the data frame.
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”,…..)
Sam Firke's ever useful package janitor
has a function especially for this: row_to_names
.
Example from his documentation:
library(janitor) x <- data.frame(X_1 = c(NA, "Title", 1:3), X_2 = c(NA, "Title2", 4:6)) x %>% row_to_names(row_number = 2)
header.true <- function(df) { names(df) <- as.character(unlist(df[1,])) df[-1,] }
Test
df1 <- data.frame(c("a", 1,2,3), c("b", 4,5,6)) header.true(df1) a b 2 1 4 3 2 5 4 3 6
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