使用 dplyr 更改行文本
Change Row Text using dplyr
想问下dplyr能不能改行文字。例如,如果我有这样的 table:
Fruit Cost
apple 6
apple 7
orange 3
orange 4
如何使用 dplyr 将 Fruit 列中的所有 "apple" 更改为 "lemon"。如果 dplyr 不能做到这一点,R 中是否有任何函数可以做到这一点(假设我有大量行需要更改)。谢谢
要使用 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"
如果它原来是一个因子,将它转换回来:
d$Fruit <- as.factor(d$Fruit)
您也可以使用 car
中的 recode
。这适用于 factor
和 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
将 class 更改为 '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
数据
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")
想问下dplyr能不能改行文字。例如,如果我有这样的 table:
Fruit Cost
apple 6
apple 7
orange 3
orange 4
如何使用 dplyr 将 Fruit 列中的所有 "apple" 更改为 "lemon"。如果 dplyr 不能做到这一点,R 中是否有任何函数可以做到这一点(假设我有大量行需要更改)。谢谢
要使用 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"
如果它原来是一个因子,将它转换回来:
d$Fruit <- as.factor(d$Fruit)
您也可以使用 car
中的 recode
。这适用于 factor
和 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
将 class 更改为 '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
数据
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")