Home > other >  R Date format changed after sapply
R Date format changed after sapply

Time:11-04

age <- c(22,24,NA,27)
duedate <- as.Date(c("1/1/2020",NA,"1/30/2020","12/31/2021"), format="%m/%d/%Y")
df <- data.frame(age,duedate)

Minimum <- sapply(df, function(x) min(x,na.rm=T))
Maximum <- sapply(df, function(x) max(x,na.rm=T))
tbl <- data.frame(min_scale,max_Scale)
print(tbl)
tbl[2,1] <- as.Date(tbl[2,1],origin = "1970-01-01") #Do not work

enter image description here enter image description here

After making the table, the dates were changed to numeric values and I can't return it back. Any suggestion? I want to show the dates like the right table. I want to do it automatically as much as possible as I have lots of variables.

CodePudding user response:

A solution using dplyr and tidyr. This will work for multiple columns.

library(dplyr)
library(tidyr)

df2 <- df %>%
  summarize(across(.fns = list(Min = min, Max = max), na.rm = TRUE)) %>% # Apply min and max function
  mutate(across(.fns = as.character)) %>%                                # Convert all columns to character
  pivot_longer(everything(), names_to = "Parameter") %>%                 # Convert to long format
  separate(Parameter, into = c("Parameter", "Statistics")) %>%           # Separate the Parameter columns
  pivot_wider(names_from = "Statistics", values_from = "value")          # Convert to wide format

df2
# # A tibble: 2 x 3
#   Parameter Min        Max       
#   <chr>     <chr>      <chr>     
# 1 age       22         27        
# 2 duedate   2020-01-01 2021-12-31  

CodePudding user response:

This is a bit simpler and results in a data frame in the same orientation as df with the age and duedate in separate columns:

tbl <- as.data.frame(rbind(Minimum, Maximum))
tbl$duedate <- as.Date(tbl$duedate, "1970-01-01")
tbl
#         age    duedate
# Minimum  22 2020-01-01
# Maximum  27 2021-12-31
  • Related