onhalu
onhalu

Reputation: 745

Multiple column mutate

I have a big data table with 100+ columns and I would like to change values in selected ones. I would like to select the columns by column names.

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"))

I would like change columns xy_Date and ab_Date from character type to date.

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

But is there a solution with base R?

Upvotes: 0

Views: 128

Answers (3)

akrun
akrun

Reputation: 886938

IN base R

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

-output

> 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"

Upvotes: 1

Sakshi Maurya
Sakshi Maurya

Reputation: 51

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"

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388797

In base R, you can use 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"

Upvotes: 1

Related Questions