【问题标题】:Multiple column mutate多列变异
【发布时间】:2021-08-10 09:20:13
【问题描述】:

我有一个包含 100 多列的大数据表,我想更改选定列中的值。我想按列名选择列。

df <- data.frame(
  xy_Date = c("2018-12-03","2019-01-02","2019-02-03"),
  ab_Date = c("2018-05-03","2019-10-02","2019-12-03"),
  names = c("Kevin", "Mark", "Jon"))

我想将 xy_Date 和 ab_Date 列从字符类型更改为日期。

library(dplyr)    
df %>% mutate(across(grep("Date", names(df)), ~ as.Date(as.character(.x), "%Y-%m-%d ")))

但是有没有基于 R 的解决方案?

【问题讨论】:

  • 虽然您的dplyr 代码有效,但在dplyr 中有starts_with/contains 等功能可以选择列。在这里你可以通过df %&gt;% mutate(across(contains('Date'), as.Date)) 得到相同的输出。

标签: r dplyr multiple-columns


【解决方案1】:

在base R中,你可以使用lapply -

cols <- grep("Date", names(df))
df[cols] <- lapply(df[cols], as.Date)
df

#     xy_Date    ab_Date names
#1 2018-12-03 2018-05-03 Kevin
#2 2019-01-02 2019-10-02  Mark
#3 2019-02-03 2019-12-03   Jon

str(df)
#'data.frame':  3 obs. of  3 variables:
# $ xy_Date: Date, format: "2018-12-03" "2019-01-02" "2019-02-03"
# $ ab_Date: Date, format: "2018-05-03" "2019-10-02" "2019-12-03"
# $ names  : chr  "Kevin" "Mark" "Jon"

【讨论】:

    【解决方案2】:
    library(dplyr)
    df <- data.frame(
      xy_Date = c("2018-12-03","2019-01-02","2019-02-03"),
      ab_Date = c("2018-05-03","2019-10-02","2019-12-03"),
      names = c("Kevin", "Mark", "Jon"))   
    
    new_col_df = df %>% mutate_at(vars(contains('Date')),as.Date)
    str(new_col_df)
    
    ## Output
    # str(new_col_df)
    # 'data.frame': 3 obs. of  3 variables:
    # $ xy_Date: Date, format: "2018-12-03" "2019-01-02" "2019-02-03"
    # $ ab_Date: Date, format: "2018-05-03" "2019-10-02" "2019-12-03"
    #  $ names  : chr  "Kevin" "Mark" "Jon"
    

    【讨论】:

      【解决方案3】:

      输入base R

      df[endsWith(names(df), "Date")] <- lapply(df[endsWith(names(df), "Date")], as.Date)
      

      -输出

      > str(df)
      'data.frame':   3 obs. of  3 variables:
       $ xy_Date: Date, format: "2018-12-03" "2019-01-02" "2019-02-03"
       $ ab_Date: Date, format: "2018-05-03" "2019-10-02" "2019-12-03"
       $ names  : chr  "Kevin" "Mark" "Jon"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-01-19
        • 1970-01-01
        • 1970-01-01
        • 2020-07-17
        • 1970-01-01
        • 1970-01-01
        • 2022-01-02
        相关资源
        最近更新 更多