使用t()%*%时出现R错误消息“需要数字/复杂矩阵/矢量参数" [英] R error message when using t()%*% "requires numeric/complex matrix/vector arguments"
问题描述
我正在从事社交网络分析任务,需要从矩阵创建网络.我正在尝试创建一个矩阵,该矩阵显示哪些学生通过他们共同的课程链接或不链接(一个人对人的矩阵).我已经将原始数据整理到矩阵的第一次迭代中,现在想乘以该矩阵.我的数据集和当前矩阵是以下内容的较大版本:
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")
当我运行矩阵乘法代码时,我得到以下错误消息:t(m)%*%m中的错误:需要数字/复数矩阵/矢量参数.
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
先前的SO问答矩阵乘法R:需要数字/复杂矩阵/向量参数建议矩阵需要包含数字或因子值,因此我添加了以下代码,但得到了相同的错误消息:
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.对不起,丑陋的代码……R的新手.
P.S. Sorry for ugly code…new to R.
推荐答案
这可能有帮助:
# 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
这篇关于使用t()%*%时出现R错误消息“需要数字/复杂矩阵/矢量参数"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!