2016-03-17 55 views
0

我有一个数据集,我的所有数据都是分类的,我想用一个热门编码进行进一步分析。复杂变量的一个热门编码

我想主要问题需要解决:

  • 一些细胞中含有很多的文字在一个单元(一个例子如下)。
  • 某些数值需要更改为进一步处理的因素。

数据与3个标题的时代,信息&目标

mydf <- structure(list(Age = c(99L, 10L, 40L, 15L), Info =   c("c(\"good\", \"bad\", \"sad\"", 
"c(\"nice\", \"happy\", \"joy\"", "NULL", "c(\"okay\", \"nice\", \"fun\", \"wild\", \"go\"" 
), Target = c("Boy", "Girl", "Boy", "Boy")), .Names = c("Age", 
"Info", "Target"), row.names = c(NA, 4L), class = "data.frame") 

我想创建上面显示所有这些变量中的一个热点编码,以便它看起来像下面这样:

 Age_99 Age_10 Age_40 Age_15 good bad sad nice happy joy null okay nice fun wild go Boy Girl 
     1  0  0  0  1 1 1 0  0 0 0 0 0 0 0 0 0 0 
     0  1  0  0  0 0 0 1  1 1 0 0 0 0 0 0 0 1 

我已经检查过的一些问题是thisthis

+0

你是怎么得到这个数据在这种形式开始?你能为我们输入这几行吗? – A5C1D2H2I1M1N2O1R2T1

回答

0

您可以使用grepl函数来扫描每个字符串以查找任何内容,并使用ifelse来适当地填充列。 喜欢的东西:

# This will create a new column labeled 'good' with 1 if the string contains and 0 if not 
data$good = ifelse(grepl("good",data$info),1, 0) 
# and do this for each variable of interest 

,并在结束时,你可以删除info列,如果你愿意的话。这样你就不必制作任何新的数据表。

data$info <- NULL 

请注意,您应该将'数据'更改为您的数据集的实际名称。 至于随着年龄的问题,没有必要把它变成因素,只需使用:

data$age99 = ifelse(data$Age == 99, 1,0) # and so forth for the other ages

+0

谢谢,但对我来说主要问题是现在一个热门的编码。 –

2

我会假设下面应该工作:

library(splitstackshape) 
library(magrittr) 

suppressWarnings({        ## Just to silence melt 
    mydf %>%          ## The dataset 
    as.data.table(keep.rownames = TRUE) %>%  ## Convert to data.table 
    .[, Info := gsub("c\\(|\"", "", Info)] %>% ## Strip out c(and quotes 
    cSplit("Info", ",") %>%      ## Split the "Info" column 
    melt(id.vars = "rn") %>%      ## Melt everyting except rn 
    dcast(rn ~ value, fun.aggregate = length) ## Go wide 
}) 
# rn 10 15 40 99 Boy Girl NULL bad fun go good happy joy nice okay sad wild NA 
# 1: 1 0 0 0 1 1 0 0 1 0 0 1  0 0 0 0 1 0 2 
# 2: 2 1 0 0 0 0 1 0 0 0 0 0  1 1 1 0 0 0 2 
# 3: 3 0 0 1 0 1 0 1 0 0 0 0  0 0 0 0 0 0 4 
# 4: 4 0 1 0 0 1 0 0 0 1 1 0  0 0 1 1 0 1 0 

这是我使用的样品数据:

mydf <- structure(list(Age = c(99L, 10L, 40L, 15L), Info = c("c(\"good\", \"bad\", \"sad\"", 
    "c(\"nice\", \"happy\", \"joy\"", "NULL", "c(\"okay\", \"nice\", \"fun\", \"wild\", \"go\"" 
    ), Target = c("Boy", "Girl", "Boy", "Boy")), .Names = c("Age", 
    "Info", "Target"), row.names = c(NA, 4L), class = "data.frame") 
+0

@手推车和马海毛为你的答案,但我有几个问题..你从哪里得到变量“rn”。此外,你只分裂变量“信息”,但“年龄”&目标也分裂。这是cSplit库的一个规范,还是可以选择哪些变量分割哪些不分割。谢谢 –