首页 > 解决方案 > R-在特定刺痛/模式之后将行添加到数据框

问题描述

我正在尝试在我的数据框中填写一些缺失的数据,如下所示:

ID  Value
1234    0001A
Text    Text 2
1235    0001A
1236    0001A
Text    Text 2
1237    0001A
1238    0001A
1239    0001A
Text    Text 2
1240    0001A

ID我想要的是在我想要插入一行的每个数值之后Text,所以最终结果是:

ID  Value
1234    0001A
Text    Text 2
1235    0001A
Text    
1236    0001A
Text    Text 2
1237    0001A
Text    
1238    0001A
Text    
1239    0001A
Text    Text 2
1240    0001A
Text    

我找到了这个答案,并尝试根据我的要求调整它,但没有任何乐趣。 根据 NA 值的存在回答添加行

例子

df <- structure(list(ID = c("1234", "Text", "1235", "1236", "Text", "1237", "1238", "1239", "Text", "1240"), Value = structure(c(1L, 
2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L), .Label = c("0001A", "Text 2"), class = "factor")), row.names = c(NA, -10L), class = "data.frame")

注意:ID 列作为字符元素存在。

标签: rdataframerow

解决方案


稍后我们可以添加行号作为arrange对数据的引用。

library(dplyr)
df <- df %>% mutate(row = row_number())

过滤其中有数字ID但后面没有 a的行'Text',将ID值更改为'Text'Value为空字符串并绑定到原始数​​据框和arrange

df %>%
  filter(grepl('\\d+', ID) & lead(ID, default = last(ID)) != 'Text') %>%
  mutate(ID = 'Text', Value = '') %>%
  bind_rows(df) %>%
  arrange(row, desc(Value)) %>%
  select(-row)


#     ID  Value
#1  1234  0001A
#2  Text Text 2
#3  1235  0001A
#4  Text       
#5  1236  0001A
#6  Text Text 2
#7  1237  0001A
#8  Text       
#9  1238  0001A
#10 Text       
#11 1239  0001A
#12 Text Text 2
#13 1240  0001A
#14 Text       

推荐阅读