1

I have a data frame a

> a        # a is a data frame
      X1.4
one      1
two      2
three    3
four     4

when I want to remove a row

> a = a[-2,] # remove row 2

it turns into numeric values

> a
[1] 1 3 4

Why?? I want to keep them as data frame with the same row names and column names

Here's the dput:

> dput(a)
structure(list(X1.4 = 1:4), class = "data.frame", row.names = c("one", 
"two", "three", "four"))
Math Avengers
  • 762
  • 4
  • 15

1 Answers1

1

We can use drop = FALSE

a[-2, , drop = FALSE]
#      X1.4
#one      1
#three    3
#four     4

as the ?Extract by default shows drop = TRUE

x[i, j, ... , drop = TRUE]

and in the details, it says

drop - For matrices and arrays. If TRUE the result is coerced to the lowest possible dimension (see the examples). This only works for extracting elements, not for the replacement. See drop for further details.


Or with tidyverse, using slice

 library(dplyr)
 library(tibble)
 a %>%
    rownames_to_column('rn') %>%
    slice(-2) %>%
    column_to_rownames('rn')
 #      X1.4
 #one      1
 #three    3
 #four     4
akrun
  • 874,273
  • 37
  • 540
  • 662