【问题标题】:how can I split in r text in frequency matrix? [duplicate]如何在频率矩阵中拆分 r 文本? [复制]
【发布时间】:2016-02-06 11:51:57
【问题描述】:

从使用

导入的数据开始
dati<- ( read.csv(file='C:...csv', header=TRUE, sep=";"))

我选择了两个变量

id<-dati$post_visid_low
item<-dati$event_list

id<-as.character(id)
item<-as.character(item)

dataT &lt;- data.table(id, item) dataT的结构是

id   item
1    102, 104, 108,401
2    405, 103, 650, 555, 450
3    305, 109

我想获得这个带有有序列的频率矩阵

id  102  103  104  108 109  305  401   405   450    555   650
1    1         1    1
2         1                             1     1      1
3                        1    1

我该怎么做? 我试过了

library(Matrix)
id<-as.character(id)
item<-as.character(item)
dataT <- data.table(id, item)
lst <- strsplit(dataT$item, '\\s*,\\s*')
Un1 <- sort(unique(unlist(lst)))
sM <-  sparseMatrix(rep(dataT$id, length(lst)), 
                    match(unlist(lst), Un1), x= 1, 
                    dimnames=list(dataT$id, Un1))

但我收到此错误

Error in i + (!(m.i || i1)) : non-numeric argument to binary operator

我该怎么做?

【问题讨论】:

  • 扩展你的拆分项目的方法,你可以做idx &lt;- with(d, sort(unique(as.numeric(unlist(strsplit(item, ",")))))); s &lt;- sapply(idx, function(x) grepl(x, d$item)) + 0L ; colnames(s) &lt;- idx [这是nice,因为它几乎使用了每个函数基R]

标签: r


【解决方案1】:

我们可以使用包 splitstackshape 来帮助我们进行拆分,然后结合融合和 dcasting 来获取您指定的格式的数据(请注意,使用数字列名并不总是可行的。

library(splitstackshape)

# split the data
step1 <- cSplit(dat, splitCols="item")
step1
#    id item_1 item_2 item_3 item_4 item_5
# 1:  1    102    104    108    401     NA
# 2:  2    405    103    650    555    450
# 3:  3    305    109     NA     NA     NA

# reshape it and remove missings
step2 <- melt(step1, id.vars="id")[!is.na(value),]

# turn to wide
output <- dcast(step2, id~value, fun.aggregate = length)

# or in one line

output <- dcast(melt(cSplit(dat, splitCols="item"), id.vars="id")[!is.na(value),], 
                id~value, fun.aggregate = length)

output
#    id 102 103 104 108 109 305 401 405 450 555 650
# 1:  1   1   0   1   1   0   0   1   0   0   0   0
# 2:  2   0   1   0   0   0   0   0   1   1   1   1
# 3:  3   0   0   0   0   1   1   0   0   0   0   0

或者,您可以使用同一包中的cSplit_e

cSplit_e(dat, "item", ",", type = "character", fill = 0, drop = TRUE)
  id item_102 item_103 item_104 item_108 item_109 item_305 item_401 item_405 item_450 item_555 item_650
# 1  1        1        0        1        1        0        0        1        0        0        0        0
# 2  2        0        1        0        0        0        0        0        1        1        1        1
# 3  3        0        0        0        0        1        1        0        0        0        0        0

使用的数据:

dat <- data.frame(id=1:3, item=c("102, 104, 108,401","405, 103, 650, 555, 450","305, 109"))

【讨论】:

    猜你喜欢
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多