How to automatically shrink down row numbers in R data frame when removing rows in R

时光怂恿深爱的人放手 提交于 2020-01-22 20:15:57

问题


I'm having a difficulty properly shrinking down the row numbers in a data frame.

I have a data set named "mydata" which I imported from a text file using R. The data frame has about 200 rows with 10 columns.

I removed the row number 3, 7, 9, 199 by using:

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

When I run this command, the row 3,7,9,199 are gone from the list but the row number doesn't automatically shrink down to 196, but stays at 200. I feel like somehow these row numbers are attached to each "row" as part of the dataframe?

How do I fix this problem?

What puzzles me even more is that when I import the textfile using R Studio, I don't have any problem. (I see 196 when I run the above command). But when using R, I can't change the row number in a dataframe that matches the actual number of rows in the list.

Can anyone please tell me how to fix this??


回答1:


You can simply do:

rownames(mydata) <- NULL

after performing the subsetting.

For example:

> mydata = data.frame(a=1:10, b=11:20)
> mydata = mydata[-c(6, 8), ]
> mydata
    a  b
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
   a  b
1  1 11
2  2 12
3  3 13
4  4 14
5  5 15
6  7 17
7  9 19
8 10 20



回答2:


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

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

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

eg

library(data.table)

mydata <- data.table(mydata)
mydata
##      a  b
##  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
##     a  b
## 1:  1 11
## 2:  2 12
## 3:  3 13
## 4:  4 14
## 5:  5 15
## 6:  7 17
## 7:  9 19
## 8: 10 20


来源:https://stackoverflow.com/questions/12361471/how-to-automatically-shrink-down-row-numbers-in-r-data-frame-when-removing-rows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!