I need access a tibble table that is in a nest()
function inside of another nest()
function.
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()
What am I trying to do is applying a function inside of first vector, something like:
test <- function(df){
df$data %>%
mutate(increa = cost + 15)
}
x2$data%>%
map(test)
dput(x2)
result a:
structure(list(scene = 1:4, data = list(structure(list(client = structure(1L, .Label = "factory", class = "factor"), data = list(structure(list(cost = c(21, 30, 44, 100), type = c("a", "b", "c", "d")), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame")))), row.names = c(NA, -1L), class = c("tbl_df", "tbl", "data.frame")), structure(list(client = structure(1L, .Label = "factory", class = "factor"), data = list(structure(list(cost = c(21, 30, 44, 100), type = c("a", "b", "c", "d")), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame")))), row.names = c(NA, -1L), class = c("tbl_df", "tbl", "data.frame")), structure(list(client = structure(1L, .Label = "factory", class = "factor"), data = list(structure(list(cost = c(21, 30, 44, 100), type = c("a", "b", "c", "d")), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame")))), row.names = c(NA, -1L), class = c("tbl_df", "tbl", "data.frame")), structure(list(client = structure(1L, .Label = "factory", class = "factor"), data = list(structure(list(cost = c(21, 30, 44, 100), type = c("a", "b", "c", "d")), 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"))
The expected result:
[[1]]
[[1]]$`factory`
[1] "a" "b" "c" "d"
[[1]]$cost
[1] 21 30 44 100
[[1]]$increa
[1] 36 45 59 115
[[2]]
[[2]]$`factory`
[1] "a" "b" "c" "d"
[[2]]$cost
[1] 21 30 44 100
[[2]]$increa
[1] 36 45 59 115
[[3]]
[[3]]$`factory`
[1] "a" "b" "c" "d"
[[3]]$cost
[1] 21 30 44 100
[[3]]$increa
[1] 36 45 59 115
[[4]]
[[4]]$`factory`
[1] "a" "b" "c" "d"
[[4]]$cost
[1] 21 30 44 100
[[4]]$increa
[1] 36 45 59 115
Someone could help me to solve this issue?
ANSWER
This is the result that I was looking for:
map(x2$data, function(df) map(df$data, function(df) df <- mutate(df,increa = cost + 15)))
}
in your example code. – MrFlickx2 %>% mutate(data = map(data, test))
, but the problem is that your datasets in the data column don't have a data column themselves and thus the test function is not working--- If you remove the$data
in your test function does it give you your desired output? – kath