转换具有 2 列和行分隔符的 R 数据帧



我有一个数据帧,它有两列"id"和"detail"(df_current下面)。我需要按 id 对数据帧进行分组,并展开文件,使列变为"接口 1"、"接口 2"等,并且接口列下的内容是每次出现接口值时的即时值。本质上,"!" 用作分隔符,但在输出中不需要它。

所需的输出如下所示:"df_needed_from_current"。

我已经尝试了多种方法(group_by,传播,重塑,dcast等),但无法使其工作。任何帮助将不胜感激!

示例当前数据帧(要创建的代码):

12
id detail
1
接口1
1安培
1字节
1
1接口2
1安培
1字节
2
2接口1
2安培
2字节
2c
2
接口2
2安培
3
3接口1
3安培
3字节
3c
3
我们删除了 "detail" 值"!"

的行,然后创建一个新的列 'interface',其中只有前缀 'interface' 的值来自 'detail', 使用fillfromtidyr用以前的非 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>    

最新更新