Adding new column with diff() function when there is one less row in R

六眼飞鱼酱① 提交于 2019-11-28 11:46:59
G. Grothendieck

Here are two approaches. Both put an NA in the first row of diff_qsec and put diff(qsec) in the remaining rows:

library(dplyr)  
mtcars %>% mutate(diff_qsec = qsec - lag(qsec)) # dplyr has its own version of lag

transform(mtcars, diff_qsec = c(NA, diff(qsec)))

Also, on the general issue of padding see: How can I pad a vector with NA from the front?

You could use the base function within() like so:

mtcars <- within(mtcars, difference <- c(NA,diff(qsec)))

This creates a column called "difference" with the first element NA and the rest calculated by diff(qsec).

You could create more columns at the same time by wrapping commands in {}, such as:

mtcars <- within(mtcars, {difference <- c(NA,diff(qsec))
                         multiple <- qsec*2})

Note that you must use <- for the assignment and not =.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!