4

I want to ask if dplyr can change the row text. For example, if I have a table like this:

Fruit     Cost
apple      6
apple      7
orange     3
orange     4

How can I change all "apple" in Fruit column to "lemon" using dplyr. If dplyr cannot do that, is there any function in R can do that (assuming I have a large numbers of row need to change). Thanks.

kelvinfrog
  • 435
  • 1
  • 8
  • 18

2 Answers2

7

To do this using dplyr you'd want to use mutate() and and ifelse() statement I think. But I think the non-dplyr option probably is easier. The first step may be unnecessary if your Fruit column is already character:

d$Fruit <- as.character(d$Fruit)

##  The dplyr option:
#d %>% mutate( Fruit=ifelse(Fruit=="apple","lemon", Fruit ) )

##  The base R option:
d$Fruit[ d$Fruit == "apple" ] <- "lemon"

And if it was originally a factor, convert it back:

d$Fruit <- as.factor(d$Fruit)
Forrest R. Stevens
  • 3,435
  • 13
  • 21
6

You may also use recode from car. This would work with both factor and character class

library(dplyr)
library(car)
res <- mutate(df1, Fruit= recode(Fruit, "'apple'='lemon'"))
res
#    Fruit Cost
#1  lemon    6
#2  lemon    7
#3 orange    3
#4 orange    4

str(res) 
#'data.frame':  4 obs. of  2 variables:
# $ Fruit: Factor w/ 2 levels "lemon","orange": 1 1 2 2
# $ Cost : int  6 7 3 4

Changing the class to 'character'

 df1$Fruit <- as.character(df1$Fruit)
 str(mutate(df1, Fruit= recode(Fruit, "'apple'='lemon'")))
 #'data.frame': 4 obs. of  2 variables:
 #$ Fruit: chr  "lemon" "lemon" "orange" "orange"
 #$ Cost : int  6 7 3 4

data

df1 <- structure(list(Fruit = structure(c(1L, 1L, 2L, 2L),
.Label = c("apple", 
"orange"), class = "factor"), Cost = c(6L, 7L, 3L, 4L)),
.Names = c("Fruit", 
"Cost"), row.names = c(NA, -4L), class = "data.frame")
akrun
  • 874,273
  • 37
  • 540
  • 662
  • what if I want to change multiple items instead of just apple to lemon. I tried this: mutate(df1, Fruit= recode(Fruit, "'apple'='lemon'", "'orange'='grape'")) but it does not work. I tried with both class as character and factor but both say Error in if (as.factor.result). Thanks. – kelvinfrog May 13 '15 at 19:11
  • 1
    Try `;` as separator. `mutate(df1, Fruit= recode(Fruit, "'apple'='lemon'; 'orange'='grape'"))` – akrun May 13 '15 at 19:14