Science_blog: How to insert date in row in R

Search This Blog

Tuesday, 28 February 2023

How to insert date in row in R

 #########Import your file#########

> culti <- read.csv("cultivation2.csv", header = TRUE, sep = ",")

> culti$date <- as.Date(culti$hdate)

> cult2 <- data.frame(culti$date,   culti$site,    culti$code)

> colnames(cult2) <- c("date", "site", "crop")

> cutiec1 <- cult2 %>%

  filter(site == 1)


###########Do not forget to check your structure of data#######

> str(cutiec1) ("It should be character otherwise it would not work")

'data.frame': 11 obs. of  3 variables:

 $ date: Date, format: "2009-12-12" ...

 $ site: int  1 1 1 1 1 1 1 1 1 1 ...

 $ crop: chr  "CC" "SM" "WW" "WR" ...

####Change date to character format all rows

> cutiec1$date <- as.character(cutiec1$date)

> cutiec1$site <- as.character(cutiec1$site)

###option 1#####

> cutiec1[nrow(cutiec1)+ 1, ] <- c("2018-09-29")

but this would create problems like this 

date       site       crop

1  2009-08-02          1       <NA>

2  2009-12-12          1         CC

3  2010-10-14          1         SM

4  2011-07-28          1         WW

5  2012-07-20          1         WR

6  2013-08-04          1         WW

7  2013-12-11          1         CC

8  2014-10-09          1         SM

9  2015-07-22          1         WW

10 2016-11-01          1         GM

11 2017-07-30          1         WW

12 2018-07-09          1         WR

13 2018-09-29 2018-09-29 2018-09-29

Hence follow this ---

############Option 2##########

> cutiec1 <- cutiec1 %>% add_row(date="2009-08-02", site="1", .before = 1)

> cutiec1 <- cutiec1 %>% add_row(date="2018-09-29", site="1", .after = 12)

######then character date to POSIXct date

> cutiec1$date <- as.POSIXct(cutiec1$date, tz = "UTC")

#########Then convert POSIXct date to date format

> cutiec1$date <- as.Date(cutiec1$date)

Then do "pad". It will creat date from 2009-08-02 to 2018-09-29 at interval of day

> cutiec12 <- pad(cutiec1, interval = "day",)


It shows 3346 variables for all 9 years on daily basis.


#############################Done##############################################

No comments:

Post a Comment

Multidisciplinary Mega‑Journals: Has Their Time Passed?

     Over the past decade, multidisciplinary and so‑called “mega‑journals” became some of the most attractive destinations for researchers u...