Home > other >  Set values to 0 if rownames contains specific words in R
Set values to 0 if rownames contains specific words in R

Time:02-16

Consider the following data.frame in R:

df <- data.frame(Agriculture = c(2,7,2),
                 Fishery     = c(1,4,7),
                 Industry    = c(5,7,3))

rownames(df) <- t(colnames(df))

If the rownames is "Fishery" or "Industry", I want to set the row values to 0. I could easily do it like this:

df[2:3,1:3] <- 0

However, in my case I have a big data.frame where this approach is not the best. Instead I want to define a character vector for row names matching, like this:

list_of_industries <- c("Fishery", "Industry")

And thereafter, this should be used to set the values to 0 in my df. But not sure how I should do that. How to do that in R?

CodePudding user response:

You can use the which() together with %in% to find out which row has the target rownames.

My original answer

df[which(rownames(df) %in% list_of_industries), ] <- 0

Updated answer credit to @Ritchie Sacramento

In the comment under this answer, @Ritchie Sacramento pointed out we can directly use the vector to match rownames.

df[list_of_industries, ] <- 0

Output

The two codes above generate the same output.

            Agriculture Fishery Industry
Agriculture           2       1        5
Fishery               0       0        0
Industry              0       0        0
  • Related