1

I would like to remove the rownames ONLY of the rows which contain "Apple_"

df <- data.frame('fruit'=c("Apple_1", "Apple_2", "Apple_3", "Pear_1", "Pear_2", "Pear_3"),
                'color'=c("Red", "Red", "Green","Green","Green","Green"))
df<- column_to_rownames(df, var="fruit")

None of these work because I belive there aren't any rows called just "Apple"

row.names.remove <- c("Apple")
df[!(row.names(df) %in% row.names.remove), ]
df2<- length(which(grepl("Apple", rownames(df))))

df3<- df[row.names(df) != "Apple", , drop = FALSE]
aynber
  • 22,380
  • 8
  • 50
  • 63
Ecg
  • 908
  • 1
  • 10
  • 28

1 Answers1

1

We can use grep with -

df[-grep('Apple', row.names(df)),, drop = FALSE]

Or invert = TRUE

df[grep('Apple', row.names(df), invert = TRUE),, drop = FALSE]

With data.frame, the rownames and column names attributes cannot be empty. An option is to convert it to numeric index

i1 <- grep('Apple', row.names(df))
row.names(df)[i1] <- seq_along(i1)

Or convert to a matrix and then change those row names to blank ("")

m1 <- as.matrix(df)
row.names(m1)[i1] <- ""

as matrix allows duplicated rownames while data.frame doesn't. It is also possible to completely remove the rowname attribute, but it has to be across the whole object

akrun
  • 874,273
  • 37
  • 540
  • 662
  • But that deletes the full row, I'd like to keep the rows with no name for those containing "Apple" – Ecg Mar 31 '21 at 17:38
  • @Ecg You meant to set the row names of that numbers ? – akrun Mar 31 '21 at 17:39
  • somethin like ```rownames(data) <- c()``` for those which rowname contains Apple? – Ecg Mar 31 '21 at 17:39
  • @Ecg In the example you have suffix 1, 2, 3 for Apple, do you want 1 , 2, 3 because in `data.frame`, there needs to be row name – akrun Mar 31 '21 at 17:40
  • The thing is that in my datset I will only show a selected number of rownames, so Thought deleting all the rest of unwanted rownames to plot "" for them, and the name for the ones I want. Does it make sense? – Ecg Mar 31 '21 at 17:42
  • @Ecg you could convert to `matrix` and matrix doesn't have any issue in removing the row nae attribute – akrun Mar 31 '21 at 17:43
  • 1
    @Ecg can you please check the updated solution. – akrun Mar 31 '21 at 17:45
  • Yes, this works, thanks! What is the main difference between rownames for a dataframe and a matrix then? – Ecg Mar 31 '21 at 17:47
  • 1
    @Ecg Difference is that if you do `row.names(m1) <- NULL`, it removes the rownames i.e. `dimnames(m1)` for rownames is `NULL`. The same for `row.names(df) <- NULL` resets to sequence of rows i..e 1 to 6. – akrun Mar 31 '21 at 17:49
  • 1
    @Ecg There are certain rules/features for different class and it is not good to violate those – akrun Mar 31 '21 at 17:50