微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在管道 purrr 匿名函数调用中迭代列出的数据帧

如何解决在管道 purrr 匿名函数调用中迭代列出的数据帧

使用 purrr::mapmagrittr 管道,我尝试生成一个新列,其值等于现有列的子字符串。

我可以用以下玩具数据集来说明我想做什么:

library(tidyverse)
library(purrr)

test <- list(tibble(geoid_1970 = c(123,456),name_1970 = c("here","there"),pop_1970 = c(1,2)),tibble(geoid_1980 = c(234,567),name_1980 = c("here",pop_1970 = c(3,4))
)

在每个列出的数据框中,我想要一列等于相关年份。没有迭代,我的代码是:

data <- map(test,~ .x %>% mutate(year = as.integer(str_sub(names(test[[1]][1]),-4))))

当然,这在列出的两个数据框中都返回 1970 年,这是我不想要的。 (我想要第一个是 1970 年,第二个是 1980 年。)

此外,它没有通过管道传输,我尝试通过管道传输它会引发错误

data <- test %>% map(~ .x %>% mutate(year = as.integer(str_sub(names(.x[[1]][1]),-4))))
# > Error: Problem with `mutate()` input `year`.
# > x Input `year` can't be recycled to size 2.
# > ℹ Input `year` is `as.integer(str_sub(names(.x[[1]][1]),-4))`.
# > ℹ Input `year` must be size 2 or 1,not 0.

如何使用管道遍历每个列出的数据框?

解决方法

试试:

test %>% map(~.x %>% mutate(year = as.integer(str_sub(names(.x[1]),-4))))

[[1]]
# A tibble: 2 x 4
  geoid_1970 name_1970 pop_1970  year
       <dbl> <chr>        <dbl> <int>
1        123 here             1  1970
2        456 there            2  1970

[[2]]
# A tibble: 2 x 4
  geoid_1980 name_1980 pop_1970  year
       <dbl> <chr>        <dbl> <int>
1        234 here             3  1980
2        567 there            4  1980
,

我们可以通过 parse_number

获得“年份”
library(dplyr)
library(purrr)
map(test,~ .x %>%
      mutate(year = readr::parse_number(names(.)[1])))

-输出

#[[1]]
# A tibble: 2 x 4
#  geoid_1970 name_1970 pop_1970  year
#       <dbl> <chr>        <dbl> <dbl>
#1        123 here             1  1970
#2        456 there            2  1970

#[[2]]
# A tibble: 2 x 4
#  geoid_1980 name_1980 pop_1970  year
#       <dbl> <chr>        <dbl> <dbl>
#1        234 here             3  1980
#2        567 there            4  1980

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。