set row as column in 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: convert a row to a column in r

starting_df <- data.frame(row.names= c(LETTERS[1:4]),
                          a = c(1:4),
                          b = seq(0.02,0.08,by=0.02),
                          c = c("Aaaa","Bbbb","Cccc","Dddd")
                )

Tags:

R Example