首页 > 解决方案 > 如何将单个元素中的逗号分隔值更改为多列并分配数字编码

问题描述

我从 R 中的 Google Drive 文件中提取的数据中有很多列要转换为多个列。存储数据的数据框的名称是Data

现在,让我们从 R 中提取的数据中的以下列开始,其中包含标题和前 4 个值:

Data$Param1
-----------
Private Bus, Private Car, Public Bus
Private Car, Private Van, Public Bus
Private Car
Private Bus, Private Car

从上列我们有四 (4) 组值,即:

如何将Data$Param1列转换为我上面提到的 4 个值集中的每个元素的相应列,并且在每列中,如果 Data$Param1 中不存在,则值应该为“0”,如果 Data 中存在,则值应该为“1” $参数1。

像这样:

            Data$Param1              | Data$Param1_PrivateBus | Data$Param1_PrivateCar | Data$Param1_PrivateVan | Data$Param1_PublicBus |
Private Bus, Private Car, Public Bus |          1             |            1           |            0           |           1           |
Private Car, Private Van, Public Bus |          0             |            1           |            1           |           1           |
             Private Car             |          0             |            1           |            0           |           0           |
      Private Car, Private Bus       |          1             |            1           |            0           |           0           |

我正好有 187 个相似的列来转换具有不同的值集。有些列有 5 个值,而有些列有 6、7 和 9 个值。

我正在使用 R 版本 3.4.1。

标签: rdataframe

解决方案


dplyr、stringi 和 reshape2 将完成您需要的所有工作

install.packages("dplyr")
install.packages("stringi")
install.packages("reshape2")

library(dplyr)
library(stringi)
library(reshape2)

xx_df <- data.frame(Param1 = c("Private Bus,Private Car,Public Bus", "Private Car,Private Van,Public Bus", "Private Car", "Private Bus,Private Car")
          , stringsAsFactors = F)

cbind(xx_df, stringi::stri_split_fixed(xx_df$Param1, ",", simplify = T) ) %>% 
  data.frame(stringsAsFactors = F) %>% 
  reshape2::melt(id.vars = "Param1", na.rm = T) %>% 
  mutate(variable = 1)  %>% filter(value != '') %>% 
  reshape2::dcast(Param1~value, value.var = "variable", fill = 0) %>% 
  data.frame()

结果是

                              Param1 Private.Bus Private.Car Private.Van Public.Bus
1            Private Bus,Private Car           1           1           0          0
2 Private Bus,Private Car,Public Bus           1           1           0          1
3                        Private Car           0           1           0          0
4 Private Car,Private Van,Public Bus           0           1           1          1

推荐阅读