按照 nest()
格式跟随数据库 .
x <- list( factory = c('a','b','c','d'), cost = c(21,30,44,100))
x <- as.data.frame(x)
x <- x %>%
melt('cost','factory')
colnames(x) <- c('cost','client','type')
x <- x %>%
group_by(client)%>%
nest()
for (m in 1:4) {
if(m==1){
x$scene <- m
x2 <- x
}else{
x3 <- x
x3$scene <- m
x2 <- rbind(x2,x3)
}
}
x2 <- x2 %>%
group_by(scene) %>%
nest()
它已经在使用 map()
函数,但我没有继续使用 map()
,而是在不丢失 nest()
格式的情况下更改为 pmap()
. 按照我正在使用的代码 .
test <- function(df){
mutate(df, increa = cost + 15)
}
map(x2$data, ~ map(.x$data, test))
x2_new <- x2 %>% mutate(data = map(data, function(df1) mutate(df1,
data = map(data, test))))
结果:
dput(x2_new)
结构(列表(场景= 1:4,数据=列表(结构(列表(客户端=结构(1L,.Label =“工厂”,类=“因子”)),数据=列表(结构(列表(成本= c) (21,30,44,100),type = c(“a”,“b”,“c”,“d”),increa = c(36,45,59,115)),row.names = c (NA,-4L),class = c(“tbl_df”,“tbl”,“data.frame”)))),row.names = c(NA,-1L),class = c(“tbl_df”,“ tbl“,”data.frame“)),结构(list(client = structure(1L,.Label =”factory“,class =”factor“),data = list(structure(list(cost = c)(21,30) ,44,100),type = c(“a”,“b”,“c”,“d”),increa = c(36,45,59,115)),row.names = c(NA, - 4L),class = c(“tbl_df”,“tbl”,“data.frame”)))),row.names = c(NA,-1L),class = c(“tbl_df”,“tbl”,“ data.frame“)),结构(list(client = structure(1L,.Label =”factory“,class =”factor“),data = list(结构(list(cost = c)(21,30,44,100) ),type = c(“a”,“b”,“c”,“d”),increa = c(36,45,59,115)),row.names = c(NA,-4L),class = c(“tbl_df”,“tbl”,“data.frame”)))),row.names = c(NA,-1L),class = c(“tbl_df” ,“tbl”,“data.frame”)),结构(list(client = structure(1L,.Label =“factory”,class =“factor”),data = list(structure(list(cost = c)(21) ,30,44,100),type = c(“a”,“b”,“c”,“d”),increa = c(36,45,59,115)),row.names = c(NA ,-4L),class = c(“tbl_df”,“tbl”,“data.frame”)))),row.names = c(NA,-1L),class = c(“tbl_df”,“tbl” ,“data.frame”)))),row.names = c(NA,-4L),class = c(“tbl_df”,“tbl”,“data.frame”))
该代码使用 pmap()
跟随此脚本,但我不能保持 nest()
格式
pmap(list(x2$data), ~ pmap(list(.x$data), test))