我有一个数据帧,它有两列"id"和"detail"(df_current下面)。我需要按 id 对数据帧进行分组,并展开文件,使列变为"接口 1"、"接口 2"等,并且接口列下的内容是每次出现接口值时的即时值。本质上,"!" 用作分隔符,但在输出中不需要它。
所需的输出如下所示:"df_needed_from_current"。
我已经尝试了多种方法(group_by,传播,重塑,dcast等),但无法使其工作。任何帮助将不胜感激!
示例当前数据帧(要创建的代码):
id | detail |
---|---|
1 | ! |
接口1 | |
1 | 安培 |
1 | 字节 |
1 | ! |
1 | 接口2 |
1 | 安培 |
1 | 字节 |
2 | ! |
2 | 接口1 |
2 | 安培 |
2 | 字节 |
2 | c |
2 | ! |
接口2 | |
2 | 安培 |
3 | ! |
3 | 接口1 |
3 | 安培 |
3 | 字节 |
3 | c |
3 | 天 |
"!"
的行,然后创建一个新的列 'interface',其中只有前缀 'interface' 的值来自 'detail', 使用fill
fromtidyr
用以前的非 NA 填充NA
元素,filter
"detail" 值与 'interface' 列不同的行, 使用rowid
(从data.table
开始)创建行序列 ID,并使用pivot_wider
将形状调整为"宽"格式
library(dplyr)
library(tidyr)
library(data.table)
library(stringr)
df_current %>%
filter(detail != "!") %>%
mutate(interface = case_when(str_detect(detail, 'Interface') ~ detail)) %>%
group_by(id) %>%
fill(interface) %>%
ungroup %>%
filter(detail != interface) %>%
mutate(rn = rowid(id, interface)) %>%
pivot_wider(names_from = interface, values_from = detail) %>%
select(-rn)
# A tibble: 15 x 4
# id Interface1 Interface2 Interface3
# <chr> <chr> <chr> <chr>
# 1 1 a a <NA>
# 2 1 b b <NA>
# 3 2 a a <NA>
# 4 2 b <NA> <NA>
# 5 2 c <NA> <NA>
# 6 3 a <NA> <NA>
# 7 3 b <NA> <NA>
# 8 3 c <NA> <NA>
# 9 3 d <NA> <NA>
#10 4 a a a
#11 4 b b b
#12 4 <NA> c c
#13 5 a a a
#14 5 b b b
#15 5 <NA> c <NA>