Danny Danny - 4 years ago 185
R Question

Appending Characters to Row Names Based on Condition

I have a large data frame where I would like to append characters to row names based on a condition. I have the following example:

trees <- data.frame(char = c('flower', 'cone', 'flower', 'cone'), number = c(3, 3, 5, 6))
rownames(trees) <- c('birch', 'pine', 'maple', 'redwood')

This is what I'm going for, a 'c' next to pine and redwood:

char number
birch flower 3
pine c cone 3
maple flower 5
redwood c cone 6

I know I can use paste to append characters:

# this gives the output I am looking for
paste(rownames(trees[trees$char == 'cone',]), 'c')

[1] "pine c" "redwood c"

However, when I try this following line of code, the changes don't appear in my data frame:

rownames(trees[trees$char == 'cone',]) <- paste(rownames(trees[trees$char == 'cone',]), 'c')

Answer Source

One option is

x1 <- str_extract(trees$char, "^c")
row.names(trees) <- trimws(paste(row.names(trees), replace(x1, is.na(x1), "")))
#            char number
#birch     flower      3
#pine c      cone      3
#maple     flower      5
#redwood c   cone      6

Another option is

row.names(trees) <- paste(row.names(trees), c("", "c")[(trees$char == "cone")+1])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download