Here is a sample data set:
sample1 <- data.frame(Names=letters[1:10], Values=sample(seq(0.1,1,0.1)))
When I'm reordering the data set, I'm losing the row names order
sample1[order(sample1$Values), ] Names Values 7 g 0.1 4 d 0.2 3 c 0.3 9 i 0.4 10 j 0.5 5 e 0.6 8 h 0.7 6 f 0.8 1 a 0.9 2 b 1.0
Desired output:
Names Values 1 g 0.1 2 d 0.2 3 c 0.3 4 i 0.4 5 j 0.5 6 e 0.6 7 h 0.7 8 f 0.8 9 a 0.9 10 b 1.0
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.
Method 2: Assigning row names to NULL In case, the row names are explicitly assigned to the rows, then using rownames(df) to NULL, deletes the row names and uses row numbers to access the rows.
In general, the rows are removed by using the row index number but we can do the same by using row names as well. This can be done by storing the row names that should be removed in a vector and then removing through subsetting with single square brackets as shown in the below examples.
Try
rownames(Ordersample2) <- 1:10
or more generally
rownames(Ordersample2) <- NULL
I had a dplyr usecase:
df %>% as.data.frame(row.names = 1:nrow(.))
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