在 R 中的列中填写空白行 [英] Fill out blank rows within a column in R

查看:25
本文介绍了在 R 中的列中填写空白行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们目前在某些行创建了一个名为 Change 的列,其中 0 表示公司内部新经理的变化.

We currently have made a column called Change with 0 at certain rows, indicating the change of a new manager within a firm .

<头>
公司经理季度改变
1131.12.2018
1131.03.2019
1130.06.2019
1130.09.2019
1231.12.20190
1231.03.2020
1230.06.2020
1230.09.2020

R 中是否有某种类型的函数可以填充空白行,如下表所示?不同经理在某个公司工作的时间长短各不相同.

Is there some type of function in R that can fill out the blank rows, as depicted in the table below? The length of how long the different manager works within a certain firm varies.

<头>
公司经理季度事件日期
1131.12.2018-4
1131.03.2019-3
1130.06.2019-2
1130.09.2019-1
1231.12.20190
1231.03.20201
1230.06.20202
1230.09.20203

对于糟糕的解释深表歉意.任何帮助将不胜感激.

Apologies for the poor explanation. Any help would be extremely appreciated.

推荐答案

这是一个使用滚动连接的 data.table 方法.它似乎在提供的示例数据上运行良好.change2 是您要查找的列.

Here is a data.table approach using a rolling join.. It seems to work fine on the sample data provided. change2 is the column you are looking for.

library( data.table )
DT <- fread("Firm   Manager     Quarter     Change
1   1   31.12.2018  
1   1   31.03.2019  
1   1   30.06.2019  
1   1   30.09.2019  
1   2   31.12.2019  0
1   2   31.03.2020  
1   2   30.06.2020  
1   2   30.09.2020  ")

#add id column
DT[, id := .I ]
#set key to join on
setkey( DT, id )
#perform rolling join to nearest Change == 0, get id and subtract
DT[, change2 := id - DT[Change == 0, ][DT, x.id, roll = "nearest" ] ]

#    Firm Manager    Quarter Change id change2
# 1:    1       1 31.12.2018     NA  1      -4
# 2:    1       1 31.03.2019     NA  2      -3
# 3:    1       1 30.06.2019     NA  3      -2
# 4:    1       1 30.09.2019     NA  4      -1
# 5:    1       2 31.12.2019      0  5       0
# 6:    1       2 31.03.2020     NA  6       1
# 7:    1       2 30.06.2020     NA  7       2
# 8:    1       2 30.09.2020     NA  8       3

我留在了临时列,所以你可以看到这里发生了什么.

I left in the temporary columns, so you can see what is going on here.

这篇关于在 R 中的列中填写空白行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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