Testifier
Testifier

Reputation:

Delete rows from a dataframe but keep rownames

I am using the data of the rugarch package:

  library(rugarch)
  data(sp500ret)

The data look like:

head(sp500ret)
               SP500RET
1987-03-10  0.008840447
1987-03-11 -0.001892734
1987-03-12  0.003129678
1987-03-13 -0.004577455
1987-03-16 -0.005742768
1987-03-17  0.014603325

I just want to have the first e.g. 1000 values, so I tried

sp500retmod<-sp500ret[-c(1001:length(sp500ret[,1])),1]

But this gives

head(sp500retmod)

[1]  0.008840447 -0.001892734  0.003129678 -0.004577455 -0.005742768
[6]  0.014603325

So the rownames are deleted, how can I get the first 1000 values and keep the rowname, the date?

I also tried

sp500retmod<-sp500ret[-c(1001:length(sp500ret[,1])),] 

but this does also not work.

Upvotes: 3

Views: 3442

Answers (2)

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

If you want to use the "[" function, you can use:

sp500ret[seq(1000), , FALSE]

The FALSE is an argument for the drop parameter. The default value is TRUE, but this will transform a single-column data frame into a vector. Hence the row names would be lost. If you specify FALSE, you will receive a data frame with the original row names.

Upvotes: 7

Jeremy Miles
Jeremy Miles

Reputation: 349

I think that both of these work:

d1 <- head(sp500ret, n=1000L)
rownames(d1)

d2 <- subset(sp500ret, c(1:length(SP500RET)) < 1001)
rownames(d2)

# Solution from @Penguin_Knight
d3 <- subset(sp500ret, row(sp500ret) < 1001)
rownames(d3)

Upvotes: 1

Related Questions