How to transform a key/value string into separate columns?

前端 未结 2 580
灰色年华
灰色年华 2021-01-22 11:01

I\'ve got a data.frame with key/value string column containing information about features and their values for a set of users. Something like this:

2条回答
  •  [愿得一人]
    2021-01-22 11:11

    You can use dplyr and tidyr:

    library(dplyr); library(tidyr)
    data %>% mutate(str = strsplit(str, ",")) %>% unnest(str) %>% 
             separate(str, into = c('var', 'val'), sep = ":") %>% spread(var, val, fill = 0)
    
    #   id statid 7 a b  c
    # 1  1  s003e 2 1 0  0
    # 2  2  s093u 0 1 0  4
    # 3  3  s085t 0 3 5 33
    

提交回复
热议问题