r - 改变 purrr block 中的数据列表列,并通过对数字变量进行分组来获得静态最小值

标签 r dplyr purrr

以钻石为例,我想按切割进行分组,然后为每个分组添加行号,然后进行随机播放。然后我想对价格应用转换,在本例中只是价格 + 1,然后我想找到与第 1 行相对应的价格并将其作为整个功能的值。

尝试过:

mydiamonds <- diamonds %>%
  group_by(cut) %>% 
  mutate(rownum = row_number()) %>% 
  nest %>% 
  mutate(data = map(data, ~ .x %>% sample_n(nrow(.x)))) %>% 
  mutate(data = map(data, ~ .x %>% mutate(InitialPrice = price + rownum)))

这让我很接近:

mydiamonds$data[[1]] %>% head
# A tibble: 6 x 11
  carat color clarity depth table price     x     y     z rownum InitialPrice
  <dbl> <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>  <int>        <int>
1  0.4  E     VS1      62.4  54     951  4.73  4.75  2.96  13792        14743
2  0.71 H     VS2      60.9  55    2450  5.76  5.74  3.5   20808        23258
3  1.01 F     VVS2     61    57    8688  6.52  6.46  3.96   6567        15255
4  0.62 G     VS2      61.6  55    2321  5.51  5.53  3.4   20438        22759
5  0.77 F     VS1      60.9  58    3655  5.91  5.95  3.61   1717         5372
6  1.37 G     VVS2     62.3  55.5 12207  7.05  7.14  4.43   8013        20220

我想要做的是找到与 rownum == 1 相对应的 InitialPrice 值,然后将 InitialPrice 覆盖为 mydiamonds$data 中每个数据帧的单个值。

我在最后一行尝试了一次又一次的变异,如下所示:

mutate(data = map(data, ~ .x %>% mutate(InitialPrice = price + rownum) %>% mutate(InitialPrice = . %>% filter(rownum ==1) %>% pull(InitialPrice))))

但是出现错误:

Error: Problem with mutate() input data. x Problem with mutate() input InitialPrice. x Input InitialPrice must be a vector, not a fseq/function object. ℹ Input InitialPrice is . %>% filter(rownum == 1) %>% pull(InitialPrice). ℹ Input data is map(...).

我怎样才能做到这一点?

最佳答案

我们可以将 . 括在大括号内

library(dplyr)
library(ggplot2)
library(purrr)
mydiamonds %>% 
   mutate(data = map(data, ~ .x %>% 
       mutate(InitialPrice = price + rownum ) %>%
       mutate(InitialPrice = {.} %>% 
                 filter(rownum ==1) %>% 
                 pull(InitialPrice))))
# A tibble: 5 x 2
# Groups:   cut [5]
#  cut       data                  
#  <ord>     <list>                
#1 Ideal     <tibble [21,551 × 11]>
#2 Premium   <tibble [13,791 × 11]>
#3 Good      <tibble [4,906 × 11]> 
#4 Very Good <tibble [12,082 × 11]>
#5 Fair      <tibble [1,610 × 11]> 

关于r - 改变 purrr block 中的数据列表列,并通过对数字变量进行分组来获得静态最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67511160/

相关文章:

r - 将嵌套列表转换为数据框 : extract only specific elements of interest

R Shiny 输入 slider 范围值

r - 如何在 Docker 容器中重新启动 Shiny 的服务器?

r - 基于条件语句使用 mutate() 计算有序观测值

r - dplyr 函数错误

r - 第二次使用 dplyr::do 时丢失 group_by 信息

将字符串替换为组中最长的字符串

r - docker 与 Shiny 的服务器专业版问题

r - 如何使用 dplyr 删除所有列中带有 NA 的行?

r - 计算最高进先出交易