3

I want to do an easy subtract in R, but I don't know how to solve it. I would like to know if I have to do a loop or if there is a function.

I have a column with numeric variables, and I would like to subtract n by n-1.

Time_Day Diff
10  10
15  5
45  30
60  15

Thus, I would like to find the variable "Diff".

user227710
  • 3,164
  • 18
  • 35
Marie
  • 127
  • 1
  • 9

3 Answers3

2

you can also try with package dplyr

library(dplyr)
mutate(df, dif=Time_Day-lag(Time_Day))
#   Time_Day Diff dif
# 1       10   10  NA
# 2       15    5   5
# 3       45   30  30
# 4       60   15  15
Mamoun Benghezal
  • 5,264
  • 7
  • 28
  • 33
1

Does this do what you need?

Here we save the column as a variable:

c <- c(10, 15, 45, 60)

Now we add a 0 to the beginning and then cut off the last element:

cm1 <- c(0, c)[1:length(c)]

Now we subtract the two:

dif <- c - cm1

If we print that out, we get what you're looking for:

dif # 10 5 30 15
sudo make install
  • 5,629
  • 3
  • 36
  • 48
1

With diff :

df <- data.frame(Time_Day = c(10, 15, 45, 60))
df$Diff <- c(df$Time_Day[1], diff(df$Time_Day))
df
##  Time_Day Diff
##1       10   10
##2       15    5
##3       45   30
##4       60   15

It works fine in dplyr too :

library("dplyr")
df <- data.frame(Time_Day = c(10, 15, 45, 60))
df %>% mutate(Diff = c(Time_Day[1], diff(Time_Day)))
Victorp
  • 13,636
  • 2
  • 51
  • 55