gpt4 book ai didi

r - 使用dplyr和stringr替换所有值始于

转载 作者:行者123 更新时间:2023-12-04 21:55:53 24 4
gpt4 key购买 nike

我的df

> df <- data.frame(food = c("fruit banana", "fruit apple", "fruit grape", "bread", "meat"), sold = rnorm(5, 100))
> df
food sold
1 fruit banana 99.47171
2 fruit apple 99.40878
3 fruit grape 99.28727
4 bread 99.15934
5 meat 100.53438

现在,我想替换以“水果”开头的食物中的所有值,然后按食物分组并汇总已售金额和已售金额。
> df %>%
+ mutate(food = replace(food, str_detect(food, "fruit"), "fruit")) %>%
+ group_by(food) %>%
+ summarise(sold = sum(sold))
Source: local data frame [3 x 2]

food sold
(fctr) (dbl)
1 bread 99.15934
2 meat 100.53438
3 NA 298.16776

为什么此命令不起作用?它给我NA而不是水果?

最佳答案

它对我有用,我认为您的数据有以下因素:

在按如下所示进行数据处理时使用stringsAsFactors=FALSE,或者您可以在R环境中运行options(stringsAsFactors=FALSE)以避免相同的情况:

df <- data.frame(food = c("fruit banana", "fruit apple", "fruit grape", "bread", "meat"), sold = rnorm(5, 100),stringsAsFactors = FALSE)

df %>%
mutate(food = replace(food, str_detect(food, "fruit"), "fruit")) %>%
group_by(food) %>%
summarise(sold = sum(sold))

输出:
 # A tibble: 3 × 2
food sold
<chr> <dbl>
1 bread 99.67661
2 fruit 300.28520
3 meat 99.88566

关于r - 使用dplyr和stringr替换所有值始于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43778696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com