Search code examples
rvectornested

Apply function to a certain element and rewrite the elements in another vector of a nested list


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

Solution

  • 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