R error message when using t()%*% “requires numeric/complex matrix/vector arguments”

孤街浪徒 提交于 2019-12-12 04:46:39

问题


I am working on a social network analysis assignment where I need to create a network from a matrix. I’m trying to create a matrix which shows what students are linked by classes they have in common, or not (a person-person matrix). I have wrangled the original data into the first iteration of a matrix and now want to multiply the matrix. My dataset and current matrix is a bigger version of the below:

names <- c("Tom", "Dick", "And", "Harry")
class <- c("cs1", "cs2", "cs3", "cs1")
count <- c(1, 1, 0, 1)
df = data.frame (names, class, count)
df2 <- spread(df, "class", "count")

When I run the matrix multiplication code I get this error message: Error in t(m) %*% m : requires numeric/complex matrix/vector arguments.

m <- as.matrix(df2)
m2 <- t(m) %*% m 

A previous SO question and answer Matrix multiplication in R: requires numeric/complex matrix/vector arguments suggested the matrix needed to contain numeric or factor values, so I added the below code but I got the same the error message:

df2 %>% mutate_if(is.factor, as.character) -> df2
m <- as.matrix(df2)
m2 <- t(m) %*% m 

If anyone can help me understand where I’m going wrong/ what the error message means here, I would appreciate it. Thank you!

P.S. Sorry for ugly code…new to R.


回答1:


This might help:

# fill NA with 0
df2[is.na(df2)] <- 0

# make row names the names of the people
row.names(df2) <- df2$names
df2 <- df2[,-1]

m <- as.matrix(df2)
m2 <- t(m) %*% m


来源:https://stackoverflow.com/questions/47804518/r-error-message-when-using-t-requires-numeric-complex-matrix-vector-argume

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