Home > front end >  Convert specific row to Date in R
Convert specific row to Date in R

Time:05-11

Is there a way to convert specific row value to date in R

asd <- data.frame(a = c("A", "B"), b = c(19080, "df"))

Expected output : 19080 is a date actually

asd
  a     b
1 A "2022-03-29"
2 B    df

CodePudding user response:

You can use as.Date. Since a column cannot contain a Date and a character objects, you can convert your Date object to as.character.

data.frame(a = c("A", "B"), b = c(as.character(as.Date(19080, origin = "1970-01-01")), "df"))

  a          b
1 A 2022-03-29
2 B         df

CodePudding user response:

You will never have a data.frame as you try to construct with a numeric value and a character value, so most likely you start with character values. As you want to keep your "non-dates" together with your dates in the same column, those both need to be stored as character strings. So try to make it a number and if that does not result in NA you can make it a date which you need to convert to a character string again.

asd <- data.frame(a = c("A", "B"), b = c("19080", "df"), stringsAsFactors = F)

asd %>%
  rowwise() %>%
  mutate(b = ifelse(!is.na(as.numeric(b)), as.character(as.Date(as.numeric(b), origin = "1970-01-01")), b))

#     a     b    
#   <chr> <chr>
# 1 A     19080
# 2 B     df  
  •  Tags:  
  • r
  • Related