How do I subtract columns by row?

I want to do easy subtraction in R, but I don't know how to solve it. I would like to know if I should be doing 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 "Diff" variable.

+3


source to share


3 answers


you can also try with the 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

      

+2


source


Does it do what you need it to do?

Here we are storing the column as a variable:

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

      

Now let's add 0 to the beginning and then cut off the last element:

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

      



We will now subtract two:

dif <- c - cm1

      

If we print this we get what you're looking for:

dif # 10 5 30 15

      

+1


source


From 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

:

library("dplyr")
df <- data.frame(Time_Day = c(10, 15, 45, 60))
df %>% mutate(Diff = c(Time_Day[1], diff(Time_Day)))

      

+1


source







All Articles