r - 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 列作为字符元素存在。
解决方案
稍后我们可以添加行号作为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
推荐阅读
- javascript - 与固定导航栏重叠的英雄图像幻灯片
- javascript - 如何让我的 Rect 避开另一个 Rect(画布)
- firebird - UDF Firebird 函数 STRTOINT 未在查询中定义,即使它在 RDB$FUNCTIONS 中列出
- ansible - Ansible:如何在条件下获取数组中的值
- asp.net - ASP.NET MVC - 实体框架延迟加载不使用流式 API 从相关类中检索数据
- batch-file - 如何编写一个批处理脚本,该脚本将在两个文件路径中查找可执行文件,然后运行它
- angular - 在 Angular 7 指令上测试 @HostListening('error')
- javascript - 正则表达式:匹配 <.. class='row'..> 以在 js .split() 中使用
- wordpress - Wordpress 子项 slug
- python - 是否有不允许索引的 namedtuple 便携版本?