Creating Dummy Variables from List

北慕城南 提交于 2021-02-10 03:21:15

问题


So I'm trying to create dummy variables to attach to a data frame based on whether or not a specific column of the frame has specific words in it. The column would look something like this:

 dumcol = c("good night moon", "good night room", "good morning room", "hello moon")

and I'd be creating dummy variables based on which words are contained in each row, e.g. for the first one, it contains "good", "night", and "moon", but not "room", "morning" or "hello".

The way I've been going about it so far, in a hugely primitive way, is creating a 0-valued matrix of appropriate size, and then using a for loop like so:

result=matrix(ncol=6,nrow=4)
wordlist=unique(unlist(strsplit(dumcal, " ")))
for (i in 1:6)
{ result[grep(wordlist[i], dumcol),i] = 1 }

or something similar. I'm guessing there's a faster/more resource efficient way to do it. Any advice?


回答1:


You could try:

library(tm)
myCorpus <- Corpus(VectorSource(dumcol))
myTDM <- TermDocumentMatrix(myCorpus, control = list(minWordLength = 1))
as.matrix(myTDM)

Which gives:

#         Docs
#Terms     1 2 3 4
#  good    1 1 1 0
#  hello   0 0 0 1
#  moon    1 0 0 1
#  morning 0 0 1 0
#  night   1 1 0 0
#  room    0 1 1 0

If you want the dummy variables in columns, you could use DocumentTermMatrix instead:

#    Terms
#Docs good hello moon morning night room
#   1    1     0    1       0     1    0
#   2    1     0    0       0     1    1
#   3    1     0    0       1     0    1
#   4    0     1    1       0     0    0



回答2:


Try

 library(qdapTools)
 mtabulate(strsplit(dumcol, ' '))
 #    good hello moon morning night room
 #1    1     0    1       0     1    0
 #2    1     0    0       0     1    1
 #3    1     0    0       1     0    1
 #4    0     1    1       0     0    0

Or

 library(splitstackshape)
 cSplit_e(as.data.frame(dumcol), 'dumcol', sep=' ', 
                      type='character', fill=0, drop=TRUE)
 #  dumcol_good dumcol_hello dumcol_moon dumcol_morning dumcol_night dumcol_room
 #1           1            0           1              0            1           0
 #2           1            0           0              0            1           1
 #3           1            0           0              1            0           1
 #4           0            1           1              0            0           0



回答3:


I would do

sdum <- strsplit(dumcol," ")
us   <- unique(unlist(sdum))
res  <- sapply(sdum,function(x)table(factor(x,levels=us)))
#         [,1] [,2] [,3] [,4]
# good       1    1    1    0
# night      1    1    0    0
# moon       1    0    0    1
# room       0    1    1    0
# morning    0    0    1    0
# hello      0    0    0    1

The result can be transposed with t(res) for the dummy variables in columns (the R convention).



来源:https://stackoverflow.com/questions/30513029/creating-dummy-variables-from-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!