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]]})
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
Why is the assignment to myMatrix failing within lapply and how can I get it to work (without a for loop)?
@orizon is correct about why your use of
lapplyis not working as you expected. You would have to replace<-with<<-for it to work but it is in general considered bad practice for*applyfunctions to have such side-effects.Instead, you can use