r - 如何将单个元素中的逗号分隔值更改为多列并分配数字编码
问题描述
我从 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。
解决方案
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
推荐阅读
- oop - 用继承来捕捉草书事件的 Rust 方法是什么?
- android - 带有进度条的按钮 android
- c++ - C ++试图计算用户输入特定数字的次数
- svg - 在机车滚动中使用数据滚动的 SVG 路径动画
- soap - org.apache.cxf.interceptor.Fault:解组错误:意外元素(但适用于第 7 次调用)
- javascript - 为什么我将 for 循环代码转换为 while 循环代码失败了?
- rightnow-crm - 在本地服务 Oracle 服务云客户门户?
- oauth - Openid - 有没有办法在没有重定向的情况下获取由 Challenge 方法生成的状态和随机数?
- html - 将图像添加到 div 会移动周围的 div
- c# - 如何解析json并将其反序列化为类的ObservableCollection