How to automatically compress line numbers in a data frame R when deleting rows in R

I'm having difficulty properly reducing line numbers in a data frame.

I have a dataset named "mydata" that I imported from a text file using R. A data frame has about 200 rows with 10 columns.

I deleted line number 3, 7, 9, 199 using:

mydata <- mydata[-c(3, 7, 9, 199),] 

When I run this command, line 3,7,9,199 disappeared from the list, but the line number does not automatically decrease to 196, but remains at 200. It seems to me that some line numbers are attached to each "line" as part of a data frame?

How to fix this problem?

What else puzzles me, when I import a text file using R Studio, I have no problem. (I see when I run the command above). But when using R, I cannot change the line number in the data frame that matches the actual number of lines in the list.

Can someone tell me how to fix this?

+6
source share
2 answers

You can simply do:

 rownames(mydata) <- NULL 

after performing a subset.

For instance:

 > mydata = data.frame(a=1:10, b=11:20) > mydata = mydata[-c(6, 8), ] > mydata ab 1 1 11 2 2 12 3 3 13 4 4 14 5 5 15 7 7 17 9 9 19 10 10 20 > rownames(mydata) <- NULL > mydata ab 1 1 11 2 2 12 3 3 13 4 4 14 5 5 15 6 7 17 7 9 19 8 10 20 
+9
source

You can also use the data.table package, which does not save row.names in the same way (see data.table intro , instead it will print with the line number.

See the section on how data.table works with row names and keys.

data.table inherits from data.frame , so data.table is data.frame if functions and pacakges only accept data.frames.

eg,

 library(data.table) mydata <- data.table(mydata) mydata ## ab ## 1: 1 11 ## 2: 2 12 ## 3: 3 13 ## 4: 4 14 ## 5: 5 15 ## 6: 6 16 ## 7: 7 17 ## 8: 8 18 ## 9: 9 19 ## 10: 10 20 mydata = mydata[-c(6, 8), ] mydata ## ab ## 1: 1 11 ## 2: 2 12 ## 3: 3 13 ## 4: 4 14 ## 5: 5 15 ## 6: 7 17 ## 7: 9 19 ## 8: 10 20 
+3
source

Source: https://habr.com/ru/post/925073/


All Articles