使用data.table在每组数据之后插入一行NA [英] Insert a row of NAs after each group of data using data.table

查看:61
本文介绍了使用data.table在每组数据之后插入一行NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 R 中的每组数据之后添加一行NA。

I am trying to add a row of NAs after each group of data in R.

类似前面已经问过这个问题。 在每组数据之后插入空白行

A similar question has been asked earlier. Insert a blank row after each group of data.

在这种情况下,接受的答案也可以按以下方式很好地工作。

The accepted answer works fine in this case too as follows.

group <- c("a","b","b","c","c","c","d","d","d","d")
xvalue <- c(16:25)
yvalue <- c(1:10)
df <- data.frame(cbind(group,xvalue,yvalue))
df_new <- as.data.frame(lapply(df, as.character), stringsAsFactors = FALSE)
head(do.call(rbind, by(df_new, df$group, rbind, NA)), -1 )
     group xvalue yvalue
a.1      a     16      1
a.2   <NA>   <NA>   <NA>
b.2      b     17      2
b.3      b     18      3
b.31  <NA>   <NA>   <NA>
c.4      c     19      4
c.5      c     20      5
c.6      c     21      6
c.41  <NA>   <NA>   <NA>
d.7      d     22      7
d.8      d     23      8
d.9      d     24      9
d.10     d     25     10

如何使用 data.table 处理大型data.frame来加快速度?

How can I speed this up using data.table for a large data.frame?

推荐答案

您可以尝试

df$group <- as.character(df$group)
setDT(df)[, .SD[1:(.N+1)], by=group][is.na(xvalue), group:=NA][!.N]
#     group xvalue yvalue
#1:     a     16      1
#2:    NA     NA     NA
#3:     b     17      2
#4:     b     18      3
#5:    NA     NA     NA
#6:     c     19      4
#7:     c     20      5
#8:     c     21      6
#9:    NA     NA     NA
#10:    d     22      7
#11:    d     23      8
#12:    d     24      9
#13:    d     25     10

或按照@David Arenburg的建议

Or as suggested by @David Arenburg

 setDT(df)[, indx := group][, .SD[1:(.N+1)], indx][,indx := NULL][!.N]

 setDT(df)[df[,.I[1:(.N+1)], group]$V1][!.N]

或者可以根据@eddi的评论进一步简化

Or it could be further simplified based on @eddi's comments

 setDT(df)[df[, c(.I, NA), group]$V1][!.N]

这篇关于使用data.table在每组数据之后插入一行NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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