Reputation: 1011
I have two columns that represent time, one for hour and one for the minute. The data frame looks similar to this:
hr mn
0 0
0 30
1 0
1 30
2 0
2 30
What I need is a way to paste these together to get one column hrmn
that's:
hrmn
0
30
100
130
200
230
I thought this could be done some way using paste0
but that gives me:
hrmn <- as.numeric(paste0(hr,mn))
hrmn
0
30
10
130
20
230
Is there a way to paste these two columns together and get the format i need?
Upvotes: 0
Views: 111
Reputation: 886968
We can also use strptime
after paste
ing the columns, change the format
and convert to numeric
.
as.numeric(format(strptime(do.call(paste, df1), format='%H %M'), '%H%M'))
#[1] 0 30 100 130 200 230
Upvotes: 0
Reputation: 4187
As I understand it, you want to get an hour/minute format. You could do that with:
mydf$hrmn <- paste0(sprintf("%02.0f", mydf$hr),":",sprintf("%02.0f", mydf$mn))
which gives:
> mydf
hr mn hrmn
1 0 0 00:00
2 0 30 00:30
3 1 0 01:00
4 1 30 01:30
5 2 0 02:00
6 2 30 02:30
Upvotes: 1
Reputation: 3710
df$hrmn <- df$hr*100 + df$mn
You need to check the class of columns hr
and mn
. Use class(df$hr)
and class(df$mn)
. If they are numeric, use:
df$hrmn <- df$hr*100 + df$mn
if they are characters. use:
df$hrmn <- as.numeric(df$hr*100) + as.numeric(df$mn)
Upvotes: 2