我想问一下 dplyr 是否可以更改行文本。例如,如果我有一个这样的表:
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)
关于r - 使用 dplyr 更改行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30219908/