I have a nested vector
$a
$a$age
[1] -2702 -2621 -2945
$a$gen
[1] 109 109 105
$b
$b$age
[1] -2702 -2702 -2702
$b$gen
[1] 109 109 109
I want to divide the elements of $a$age to 25, round them up and the result write in $a$gen, as well as do the same with $b$age and result write in $b$gen
So the output should be
$a
$a$age
[1] -2702 -2621 -2945
$a$gen
[1] 108 104 117
$b
$b$age
[1] -2702 -2702 -2702
$b$gen
[1] 108 108 108
CodePudding user response:
I do not know what you are trying to solve, although you could tackle the problem as :
x %>%
map_df(data.frame, .id='grp')%>%
mutate(gen = abs(ceiling(age/25)))%>%
split(~grp)%>%
map(~as.list(.x[-1]))
$a
$a$age
[1] -2702 -2621 -2945
$a$gen
[1] 108 104 117
$b
$b$age
[1] -2702 -2702 -2702
$b$gen
[1] 108 108 108
CodePudding user response:
using the previous solution:
mod_at1 <- function(x, name, FUN, new_name = NULL){
if(name %in% names(x)){
x[[if(is.null(new_name)) name else new_name]] <- FUN(x[[name]])
x
}
else if(is.list(x))lapply(x, mod_at1, name, FUN, new_name)
else x
}
mod_at1(x, 'age', function(x)abs(ceiling(x/25)), 'gen')
$a
$a$age
[1] -2702 -2621 -2945
$a$gen
[1] 108 104 117
$b
$b$age
[1] -2702 -2702 -2702
$b$gen
[1] 108 108 108