Home > Software design >  how can i change this column using R?
how can i change this column using R?

Time:12-05

This is my data frame.

borrow date   borrow time
2020-01-01     0
2020-01-01     0
2020-01-01     1
2020-01-01     1
2020-01-01     1
2020-01-01     2
2020-01-01     2
2020-01-01     2
2020-01-01     2
2020-01-01     2
2020-01-02     0
2020-01-02     1
2020-01-02     2
2020-01-02     2
2020-01-03     0
2020-01-03     0
2020-01-03     1
2020-01-03     1
2020-01-03     2

I want to change 'borrow date' column using 'borrow date' and 'borrow time'. This is what I want.

borrow date
2020-01-01 0:00
2020-01-01 0:00
2020-01-01 1:00
2020-01-01 1:00
2020-01-01 1:00
2020-01-01 2:00
2020-01-01 2:00
2020-01-01 2:00
2020-01-01 2:00
2020-01-01 2:00
2020-01-02 0:00
2020-01-02 1:00
2020-01-02 2:00
2020-01-02 2:00
2020-01-03 0:00
2020-01-03 0:00
2020-01-03 1:00
2020-01-03 1:00
2020-01-03 2:00

If I can, I want to make this code using 'for'and 'if'.

CodePudding user response:

We can use

df1$`borrow date` <- with(df1, as.POSIXct(paste(`borrow date`,
     `borrow time`), format = "%Y-%d-%d %H"))

CodePudding user response:

Here is an alternative: Note the column will stay as character class:

library(dplyr)

df %>% 
  mutate(borrowtime = paste(borrowtime, "00", sep = ":"))
   borrowdate borrowtime
1  2020-01-01       0:00
2  2020-01-01       0:00
3  2020-01-01       1:00
4  2020-01-01       1:00
5  2020-01-01       1:00
6  2020-01-01       2:00
7  2020-01-01       2:00
8  2020-01-01       2:00
9  2020-01-01       2:00
10 2020-01-01       2:00
11 2020-01-02       0:00
12 2020-01-02       1:00
13 2020-01-02       2:00
14 2020-01-02       2:00
15 2020-01-03       0:00
16 2020-01-03       0:00
17 2020-01-03       1:00
18 2020-01-03       1:00
19 2020-01-03       2:00
  • Related