purrr:modify2和Modify_at [英] purrr:modify2 and modify_at

查看:102
本文介绍了purrr:modify2和Modify_at的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下列表

df <- list(list(a = 1, b = NA_real_, c = NA_real_, d = NA_real_, e = NA_real_), 
    list(a = 1, b = NA_real_, c = NA_real_, d = NA_real_, e = NA_real_), 
    list(a = 1, b = NA_real_, c = NA_real_, d = NA_real_, e = NA_real_), 
    list(a = 1, b = NA_real_, c = NA_real_, d = NA_real_, e = NA_real_), 
    list(a = 1, b = NA_real_, c = NA_real_, d = NA_real_, e = NA_real_))

我想根据外部列表索引更改位置"a"中的值,如下所示:

I want to change the value in position "a" according the outer list index like this:

df[[1]]$a <- 1
df[[2]]$a <- 2
df[[3]]$a <- 3

但是我想使用

library(tidyverse)
df %>% 
  modify_depth(1, ~modify_at(., "a", ~. + 1))

我很确定我们可以使用 modify2 这样的东西.但不要明白.

I'm pretty sure that we can use modify2 for such thing. But don't get it.

推荐答案

与@tmfmnk基本相同,但使用的是 modify2().

Basically the same thing as @tmfmnk but using modify2().

library(purrr)

modify2(df, seq_along(df), ~ list_modify(.x, .y))

请注意,按位置更改 a .可能想做 a = .y 并更加明确.

Note that changes a by position. Probably want to do a = .y and be more explicit.

我猜这应该是:

df2 <- df %>% 
  modify2(., seq_along(.), ~ list_modify(.x, a = .y))

df2[3]

# [[1]]
# [[1]]$a
# [1] 3
# 
# [[1]]$b
# [1] NA
# 
# [[1]]$c
# [1] NA
# 
# [[1]]$d
# [1] NA
# 
# [[1]]$e
# [1] NA

看看来自@camille的另一个答案的评论,这可能是最干净的.

Looking at the comment on another answer from @camille, this may be the cleanest.

df %>% 
  imap(~ list_modify(.x, a = .y))

这篇关于purrr:modify2和Modify_at的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆