R中的数据处理,处理时间更少

时间:2018-08-27 10:55:51

标签: r

如何减少处理以下格式数据的时间?我有将近10万条格式类似的数据,其中各列可能会有所不同,因此我们在寻找通用代码,这些代码可以识别列数并提供输出。

我的实际数据看起来像

enter image description here

Verbatim <- c("dum1",   "dum2", "dum3", "dum4", "dum5")
Code_1 <- c("998 - NOTHING DISLIKED;nosort",    "066 - dislike/ contains sugar (unspecified)",  "138 - too expensive",  "127 - only good for kids", "138 - too expensive")
Code_2 <- c("", "051 - not calorie-free",   "111 - wasteful/ too much packaging",   "138 - too expensive",  "052 - high in carbohydrates")
Code_3 <- c("","","127 - only good for kids",   "067 - high in sugar",  "131 - not good for breakfast/ morning")    
Code_4 <- c("","","", "068 - dislike/ contains high fructose corn syrup",   "125 - not good for a snack")   
Code_5 <- c("","","","","123 - not good for kids")  
Code_6 <- c("","","","","017 - dislike taste of/ contains center/ filling/ stuffing (unspecified)")
Code_7 <- c("","","","","102 - messy")  
Code_8 <- c("","","","","106 - other ease of packaging comments;nosort")

Raw_data <- data.frame(Verbatim,Code_1,Code_2,Code_3,Code_4,Code_5,Code_6,Code_7,Code_8)

因此,对于上述数据,我们希望以以下方式扩展数据,其中从Code1到Code8提及的所有类别都将成为列标题(唯一值),而将针对该类别显示相应的计数。

enter image description here

Required_ouput <- data.frame(
  "Verbatim" <- c("dum1", "dum2","dum3","dum4", "dum5"),
  "998 - NOTHING DISLIKED;nosort" <- c(1, 0, 0, 0, 0),
  "066 - dislike/ contains sugar (unspecified)" <- c(0, 1, 0, 0, 0),
  "138 - too expensive" <- c(0, 0, 1, 1, 1),
  "127 - only good for kids" <- c(0, 0, 1, 1, 0),
  "051 - not calorie-free" <- c(0, 1, 0, 0, 0),
  "111 - wasteful/ too much packaging" <- c(0, 0, 1, 0, 0),
  "052 - high in carbohydrates" <- c(0, 0, 0, 0, 1),
  "067 - high in sugar" <- c(0, 0, 0, 1, 0),
  "131 - not good for breakfast/ morning" <- c(0, 0, 0, 0, 1),
  "068 - dislike/ contains high fructose corn syrup" <- c(0, 0, 0, 1, 0),
  "125 - not good for a snack" <- c(0, 0, 0, 0, 1),
  "123 - not good for kids" <- c(0, 0, 0, 0, 1),
  "017 - dislike taste of/ contains center/ filling/ stuffing (unspecified)" <- c(0, 0, 0, 0, 1),
  "102 - messy" <- c(0, 0, 0, 0, 1),
  "106 - other ease of packaging comments;nosort" <- c(0, 0, 0, 0, 1)
)

1 个答案:

答案 0 :(得分:1)

library(dplyr)
library(tidyr)
Required_ouput <- gather(Raw_data,key,val,-Verbatim) %>% select(-key) %>%
                  table() %>% as.data.frame.matrix() %>% select(-1)