change row names in dataframe r code example
Example 1: r set column values as rownames in dataframe
# Basic syntax:
rownames(your_dataframe) <- your_dataframe[,1]
your_dataframe[,1] <- NULL
# Example usage:
# Say you have the following dataframe and want to set the values of
# col1 as the rownames and then remove col1, here's how to do it
names col1 col2 col3
1 A 1 5
2 B 2 4
3 C 3 3
4 D 4 2
5 E 5 1
rownames(your_dataframe) <- your_dataframe[,1]
your_dataframe[,1] <- NULL
# Which would produce:
names col1 col2
A 1 5
B 2 4
C 3 3
D 4 2
E 5 1
Example 2: r change row names of a dataframe
# Basic syntax:
rownames(your_dataframe) <- new_names
# Note, the new_names has to be the same length as the dataframe
# Example usage:
# Say you want to set the rownames to be numbered 1-end:
rownames(your_dataframe) <- 1:nrow(your_dataframe)