Reputation: 139
I have a dataframe where one of the columns looks like this:
Minutes
1.432
12.345
4.556
1.324
0.657
6.558
I want to create a column right next to it where the whole numbers have been subtracted from the numbers. It would look like this:
Minutes
0.432
0.345
0.556
0.324
0.657
0.558
Is there a way to do this in R code?
Upvotes: 0
Views: 1002
Reputation: 887068
We can subtract from the integer version
with(df1, Minutes - as.integer(Minutes))
#[1] 0.432 0.345 0.556 0.324 0.657 0.558
library(microbenchmark)
v1 <- rep(df1$Minutes, 1e6)
microbenchmark(akrun = v1 - as.integer(v1), brittenb = v1 %%1, unit = 'relative')
#Unit: relative
# expr min lq mean median uq max neval
# akrun 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 100
# brittenb 1.386245 1.392605 1.290523 1.317515 1.232846 1.437915 100
df1 <- data.frame(Minutes = c(1.432, 12.345, 4.556, 1.324, 0.657, 6.558))
Upvotes: 2
Reputation: 7469
The comment from brittenb is quite good, just use a modulo
R> test_df <- data.frame(Minutes = c(1.432, 12.345, 4.556, 1.324,
0.657, 6.558)
R> test_df$Minutes_modulo <- test_df$Minutes %% 1
R> test_df
Minutes Minutes_modulo
1 1.432 0.432
2 12.345 0.345
3 4.556 0.556
4 1.324 0.324
5 0.657 0.657
6 6.558 0.558
From the documentation:
%% indicates x mod y and %/% indicates integer division. It is guaranteed that x == (x %% y) + y * ( x %/% y ) (up to rounding error) unless y == 0 where the result of %% is NA_integer_ or NaN (depending on the typeof of the arguments), and for non-finite arguments.
Upvotes: 2