【发布时间】:2020-08-18 09:18:24
【问题描述】:
我想做一些看起来很简单的事情,但无法得到我想要的输出
我有一堆关于日期、类别和颜色的观察
observations <- structure(list(date = structure(c(1596585600, 1596585600, 1596585600,
1596585600, 1596585600, 1596585600, 1596585600, 1596672000, 1596672000,
1596672000, 1596758400, 1596758400, 1596758400, 1596758400, 1596758400
), class = c("POSIXct", "POSIXt"), tzone = "UTC"), categorie = c("dog",
"dog", "dog", "wolf", "wolf", "wolf", "wolf", "dog", "dog", "wolf",
"dog", "wolf", "wolf", "wolf", "wolf"), color = c("blue", "blue",
"blue", "blue", "blue", "blue", "blue", "darkred", "darkred",
"darkred", "darkred", "darkred", "darkred", "darkred", "darkred"
)), row.names = c(NA, -15L), class = c("tbl_df", "tbl", "data.frame"
))
我想在一个小标题之后更改颜色属性,其中包含我想按天和类别更改的颜色数量
howmanyrainbowsiwant <-structure(list(date = structure(c(1596585600, 1596758400), class = c("POSIXct",
"POSIXt"), tzone = "UTC"), categorie = c("dog", "wolf"), makeitrainbow = c(2,
2)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
))
在这个例子中我想改变:
- 2020 年 5 月 8 日随机选择的两只狗观察到“彩虹”
- 2020 年 7 月 8 日随机选择的两个狼观察到“彩虹”
我尝试了 purr:mappp、purr:walk 和 "
library(dplyr)
library(lubridate)
library(tidyverse)
coloriage<- function(x) {
current <- tibble(x) ## make the row a variable
tirage<-current$makeitrainbow[1] ## Making the number of rainbow i want a variable
# I take a sample/slice of the datasource with the number of rainbow i want
petitsample <- observations %>%
filter(categorie %in% current$categorie ) %>%
filter(date %in% current$date ) %>%
slice_sample(tirage)
## then i save the lines in the main data but not in the slice
temp <- setdiff(observations , petitsample)
## I change the color value of the splice rows
petitsample<- petitsample %>% mutate(color= "rainbow")
## I bring back together the non modified rows and the splice modified rows
# trying with "<<-"
observations <<- bind_rows(temp, petitsample)
## And tryng with return
return(observations )
}
## Using function
walk(howmanyrainbowsiwant , coloriage)
## Checking if it worked (looking for "rainbow " values)
observations %>% count(color)
## and it fails ...
谢谢!!
ps :看起来我的reprex也可能有错误,但找不到...
【问题讨论】:
标签: r function output purrr dplyr