oercim
oercim

Reputation: 1848

Deleting a row from a data frame without loosing rownames in R

I have the below data frame(rmse1):

> rmse1
                  matrix..
1                       NA
sGARCH - norm 0.0004717566
eGARCH - norm 0.0004522429
apARCH - norm 0.0004640376
sGARCH - std  0.0004173882
eGARCH - std  0.0004546693
apARCH - std  0.0004132033
sGARCH - ged  0.0004359045
eGARCH - ged  0.0004483274
apARCH - ged  0.0004247326

or in dput format:

> dput(rmse1)
structure(list(matrix.. = c(NA, 0.0004717565532856, 0.000452242891965358, 
0.000464037577947331, 0.000417388230016878, 0.000454669306307564, 
0.00041320327280016, 0.00043590445999408, 0.00044832739721304, 
0.000424732596935747)), .Names = "matrix..", row.names = c("1", 
"sGARCH - norm", "eGARCH - norm", "apARCH - norm", "sGARCH - std", 
"eGARCH - std", "apARCH - std", "sGARCH - ged", "eGARCH - ged", 
"apARCH - ged"), class = "data.frame")

The first row is an unwanted row(where rowname is 1:)

So to delete it I type the below code:

rmse1<-rmse1[-1,]

However, this time I loose the rownames of the data frame:

> rmse1
[1] 0.0004717566 0.0004522429 0.0004640376 0.0004173882 0.0004546693 0.0004132033 0.0004359045 0.0004483274 0.0004247326

How can I delete first row without loosing the rownames.

I will be very glad for any help. Thanks a lot.

Upvotes: 1

Views: 417

Answers (2)

Arun Rawat
Arun Rawat

Reputation: 1

If it fails, try converting to data frame first!

Upvotes: 0

bouncyball
bouncyball

Reputation: 10761

The reason it's doing that is due to the drop argument.

When you subset, the array only has one level, and the default for [ is to have drop = TRUE. To counteract this, we need to specify drop = FALSE:

rmse1[-1, , drop = FALSE]

                  matrix..
sGARCH - norm 0.0004717566
eGARCH - norm 0.0004522429
apARCH - norm 0.0004640376
sGARCH - std  0.0004173882
eGARCH - std  0.0004546693
apARCH - std  0.0004132033
sGARCH - ged  0.0004359045
eGARCH - ged  0.0004483274
apARCH - ged  0.0004247326

It may be helpful to look at the strict package @hadley is developing. One of its benefits is that once it is loaded, it will throw an error if the drop argument is not specified.

Upvotes: 3

Related Questions