矩阵分配在lapply内失败 [英] matrix assignment failing within lapply

查看:112
本文介绍了矩阵分配在lapply内失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带字符数据的data.frame,我想以一个矩阵组成,该矩阵具有相同的列标题,但每个值都有计数.到目前为止,我可以得到一个我想要的尺寸的空矩阵,但是当我尝试用计数填充 myMatrix 时,它不起作用.

I have a data.frame with character data, I want to end up with a matrix with the same column headings but with counts for each value. So far I can get an empty matrix of the dimensions I want, but when I try to populate myMatrix with counts, it doesn't work.

myData <- data.frame(a=LETTERS[5:8], b=LETTERS[6:9], c=rep(LETTERS[5:6],2), d=rep(LETTERS[7],4))
#   a b c d
# 1 E F E G
# 2 F G F G
# 3 G H E G
# 4 H I F G
myValues <- sort(unique(unlist(myData))) # E F G H I
myList <- lapply(myData, table)
myMatrix <- matrix(nrow=length(myValues), ncol=length(myList), dimnames=list(myValues,names(myList)))
#    a  b  c  d
# E NA NA NA NA
# F NA NA NA NA
# G NA NA NA NA
# H NA NA NA NA
# I NA NA NA NA

到目前为止,一切都很好.这部分没有达到我的期望:

So far so good. This is the part that doesn't do what I expect:

lapply(seq_along(myList), function(i) {myMatrix[names(myList[[i]]),names(myList[i])] <- myList[[i]]})

它返回正确的值,但是 myMatrix 仍然充满NA.奇怪的是,这一作品:

It returns the right values, but myMatrix is still full of NAs. Oddly, this one works:

myMatrix[names(myList[[2]]),names(myList[2])] <- myList[[2]]
#    a  b  c  d
# E NA NA NA NA
# F NA  1 NA NA
# G NA  1 NA NA
# H NA  1 NA NA
# I NA  1 NA NA

为什么 myMatrix 的分配在 lapply 中失败,并且如何使它工作(没有 for 循环)?

Why is the assignment to myMatrix failing within lapply and how can I get it to work (without a for loop)?

推荐答案

@orizo​​n关于为什么您对 lapply 的使用无法按预期工作的说法是正确的.您必须将<-替换为<<-才能正常工作,但通常认为 * apply 不好的做法具有这种副作用.

@orizon is correct about why your use of lapply is not working as you expected. You would have to replace <- with <<- for it to work but it is in general considered bad practice for *apply functions to have such side-effects.

相反,您可以使用

sapply(lapply(myData, factor, unique(unlist(myData))), table)

#   a b c d
# E 1 0 2 0
# F 1 1 2 0
# G 1 1 0 4
# H 1 1 0 0
# I 0 1 0 0

这篇关于矩阵分配在lapply内失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆