r - 改变 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))))
然而得到错误:
错误:
mutate()
输入有问题data
。xmutate()
输入问题InitialPrice
。x 输入InitialPrice
必须是向量,而不是fseq/function
对象。ℹ 输入InitialPrice
是. %>% filter(rownum == 1) %>% pull(InitialPrice)
。ℹ 输入data
是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]>
推荐阅读
- php - 如何在 shell 中检查正确数量的 STDIN 用户输入?
- knockout.js - 使用 .extend 时如何获取底层的可观察值?
- javascript - 限制用户访问其他用户配置文件
- c# - 无法更改 DataGridView 中复选框的默认值(Windows 窗体应用程序)
- python - 如何停止在scrapy中重复循环?
- nativescript - 如何在预览模式下在 NativeScript 中构建 npm 依赖项?
- unix - Solaris 10 登录 - 接受多个密码
- mysql - 如何过滤特殊产品订单的行?
- java - 无法生成固定大小的字母数字符号字符串
- python - 网络断开时如何让我的 Python 代码重新启动