通过分组将列转换为子字段

时间:2018-06-20 10:14:38

标签: r logic

我想从中转换以下数据

[
    '_base' => '',
    '_port' => (int) 8765,
    '_scheme' => 'http',
    '_host' => 'localhost',
    'params' => [
        'pass' => [],
        'controller' => 'Roles',
        'action' => 'index',
        'prefix' => 'admin',
        'plugin' => null,
        '_matchedRoute' => '/admin/roles',
        '_ext' => null
    ]

收件人

        day fox hare wolf
1    Monday   4   20    2
2   Tuesday   4   25    1
3 Wednesday   4   30    3

我尝试使用tidyr,但似乎没有用。...

任何人,请指教。

Data manipulation reference

1 个答案:

答案 0 :(得分:1)

两种可能的方法:

1)包:

library(dplyr)
library(tidyr)

df %>% 
  gather(k, v, 2:4) %>% 
  unite('attribute', k, v, sep = '=') %>% 
  group_by(day) %>% 
  summarise(attribute = paste0(attribute, collapse = ','))

2)使用软件包:

library(data.table)

melt(setDT(df), id = 1)[, attribute := paste(variable, value, sep = '=')
                        ][, .(attribute = paste0(attribute, collapse = ',')), by = day]

两者都给出(显示{tidyverse):

# A tibble: 3 x 2
  day       attribute           
  <chr>     <chr>               
1 Monday    fox=4,hare=20,wolf=2
2 Tuesday   fox=4,hare=25,wolf=1
3 Wednesday fox=4,hare=30,wolf=3