使用dplyr更改行文本

kel*_*rog 2 r dplyr

我想询问dplyr是否可以更改行文本.例如,如果我有一个这样的表:

Fruit     Cost
apple      6
apple      7
orange     3
orange     4
Run Code Online (Sandbox Code Playgroud)

如何使用dplyr将Fruit列中的所有"apple"更改为"lemon".如果dplyr不能这样做,R中是否有任何功能可以做到(假设我需要更改大量的行).谢谢.

For*_*ens 6

要做到这一点,dplyr你想使用mutate()ifelse()我认为的陈述.但我认为非dplyr选项可能更容易.如果您的Fruit列已经是字符,则第一步可能是不必要的:

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"
Run Code Online (Sandbox Code Playgroud)

如果它最初是一个因素,请将其转换回来:

d$Fruit <- as.factor(d$Fruit)
Run Code Online (Sandbox Code Playgroud)


akr*_*run 5

您也可以使用recodefrom car。这将适用于factorcharacter

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
Run Code Online (Sandbox Code Playgroud)

将类更改为“字符”

 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
Run Code Online (Sandbox Code Playgroud)

数据

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")
Run Code Online (Sandbox Code Playgroud)