Refer to relative rows in R

后端 未结 3 479
别那么骄傲
别那么骄傲 2021-01-16 05:25

I know this answer must be out there, but I can\'t figure out how to word the question.

I\'d like to calculate the differences between values in my data.frame.

相关标签:
3条回答
  • 2021-01-16 05:31

    There are many different ways to do this, but here's one:

    f[, "diff"] <- c(NA, diff(f$value))
    

    More generally, if you want to refer to relative rows, you can use lag() or do it directly with indexes:

    f[-1,"diff"] <- f[-1, "value"] - f[-nrow(f), "value"]
    
    0 讨论(0)
  • 2021-01-16 05:31

    Use the diff function

    f <- cbind(f, c(NA, diff(f[,2])))
    
    0 讨论(0)
  • 2021-01-16 05:35

    If year column isn't sorted then you could use match:

    f$diff <- f$value - f$value[match(f$year-1, f$year)]
    
    0 讨论(0)
提交回复
热议问题