【问题标题】:R Changing format to columns of dataframes using functional programmingR使用函数式编程将格式更改为数据框列
【发布时间】:2020-07-15 22:31:46
【问题描述】:

情况如下:我有一个数据框列表,对于每个数据框,我都有一个需要更改其格式的列列表。设置:

df1 <- data.frame(a = c("2020-03-02", "2020-12-22", "2020-07-03"), b = c(4, 5, 6), c = c("2020-03-13", "2019-11-03", "2011-05-02"))

df2 <- data.frame(d = c(1, 2, 3), e = c("2020-05-21", "2014-08-31", "1999-01-21"), f = c(7, 8, 9))

datasets <- list("first" = df1, "second" = df2)

dates <- list("first" = c("a", "c"), "second" = c("e")) 

可以通过以下方式做到这一点: 1. 循环遍历数据框列表,2. 对于每个数据框,遍历想要更改的列列表,然后重新分配它们。像这样的:

for (i in names(datasets)) {
   for (j in dates[i]) {
      for (k in datasets[[i]][j]) {
         k <- as.Date(k)
      }
   }
} 

这很难看,所以我想尝试使用 purrr 来做同样的事情。我认为这是个好主意:

library(purrr)

walk2(datasets, dates, ~ walk(.x[.y], ~ {.x <- as.Date(.x)}))

但是在此操作之后数据集保持不变。为什么?

【问题讨论】:

    标签: r loops functional-programming format purrr


    【解决方案1】:

    这是一个使用 purrr 和 dplyr 的解决方案:

    library(purrr)
    library(dplyr)
    
    datasets <- datasets %>% 
      imap(~{
        .x %>% 
          mutate_at(vars(dates[[.y]]), as.Date)
      })
    
    str(datasets)
    #List of 2
    #$ first :'data.frame': 3 obs. of  3 variables:
    # ..$ a: Date[1:3], format: "2020-03-02" "2020-12-22" "2020-07-03"
    # ..$ b: num [1:3] 4 5 6
    # ..$ c: Date[1:3], format: "2020-03-13" "2019-11-03" "2011-05-02"
    #$ second:'data.frame': 3 obs. of  3 variables:
    # ..$ d: num [1:3] 1 2 3
    # ..$ e: Date[1:3], format: "2020-05-21" "2014-08-31" "1999-01-21"
    # ..$ f: num [1:3] 7 8 9
    

    【讨论】:

      猜你喜欢
      • 2016-11-14
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      相关资源
      最近更新 更多