R中的行少了时,用diff()函数添加新列 [英] Adding new column with diff() function when there is one less row in R

查看:257
本文介绍了R中的行少了时,用diff()函数添加新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个像mtcars这样的示例数据框,并且想找到所有行的mtcars $ qsec之间的区别,我可以做diff(mtcars $ qsec)。但是,有没有一种简单的方法可以使diff(mtcars $ qsec)在原始mtcars数据帧中成为新列?我发现这很困难,因为diff(mtcars $ qsec)中的行比其余mtcar少。

If I have a sample data frame like mtcars, and I want to find the difference between mtcars$qsec for all rows, I can do diff(mtcars$qsec). But is there a simple way to make diff(mtcars$qsec) a new column in the original mtcars data frame? I'm finding it difficult because there's one less row in diff(mtcars$qsec) than the rest of mtcars.

> head(mtcars,3)

               mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4     21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710    22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1


推荐答案

这里有两种方法。两者都在 diff_qsec 的第一行中放入 NA 并放入 diff(qsec)

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)))

此外,关于填充的一般问题,请参见:如何从正面填充带有NA的向量?

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

这篇关于R中的行少了时,用diff()函数添加新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆