简体   繁体   English

R:如何修复for循环,以便将行的每个元素与列的对应元素相乘?

[英]R: How can I fix my for-loop so it multiplies every element of a row with the corresponding element of a column?

I have a matrix beta with nrow=10 and ncol=10 and a second matrix data with nrow=10 and ncol=10 . 我有与基质的β nrow=10ncol=10和具有第二矩阵数据nrow=10ncol=10 I want to multiply the columns from beta with the rows from data for ever element. 我想将beta中的列乘以ever元素中数据的行。

I already tried to write a for loop: 我已经尝试编写一个for循环:

solution1 <- matrix(NA,10,10)

for(i in 1:nrow(data)){solution <- matrix(beta*data[i,])}

but this jut shows me a list of 10 times "NA" 但是这个突出显示了10次“不适用”的列表

I don't know what I am doing wrong. 我不知道我在做什么错。 I actually expect a matrix with nrow=10 and ncol=10 . 其实,我期待着与矩阵nrow=10ncol=10 Maybe someone has an idea and can help? 也许有人有主意可以提供帮助?

The operation of multiplying each element of a row of a matrix with the corresponding element of a column of another matrix is the same as the matrix multiplication defined in linear algebra. 将矩阵的一行的每个元素与另一个矩阵的一列的相应元素相乘的操作与线性代数中定义的矩阵相乘相同。

R has a matrix multiplication operator %*% R具有矩阵乘法运算符%*%

solution <- beta %*% data

After reading your clarification I found the following simple solution. 阅读您的说明后,我发现了以下简单的解决方案。 Multiplying all values element-wise and then taking the transpose of the matrix. 将所有值逐元素相乘,然后对矩阵进行转置。

solution <- t(beta*data)

Which outputs the following results 输出以下结果

     [,1] [,2] [,3]
[1,]    1    4    9
[2,]   16   25   36
[3,]   49   64   81

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 R 的 for 循环中过滤列表,以便将文件从一个文件夹移动到另一个文件夹的脚本将 function? - How can I filter a list within a for-loop in R so my script to move files from one folder to another will function? R我可以获取数据框中每一行的第一个元素吗 - R Can I get the first element for every row in a dataframe r 使用for循环从列表中提取元素 - r extract element from the list with for-loop 当我在R中输入列元素作为输入时,如何获得整行? - How can I get the whole row when I give a column's element as input in R? R 如何根据行中的相应值获取数据帧的元素? - R How to get element of data frame based on corresponding value in row? 如何使用apply而不是for-loop来检查每一行中的每一列 - How to use apply instead of for-loop to check every column in every row R - 我有一个 for 循环来识别每一行中一列的异常值 - 如何循环查看每一列? - R - I have a for loop to identify outliers in each row for one column - how to loop to look across every column? 如果元素是 R 中的特定值,如何替换列中的每个第 n 个元素 - How to replace every nth element in a column if the element is a specific value in R 在R Studio中,如何阻止我的for循环用最新的输出覆盖存储的输出? - In R Studio, how can I stop my for-loop from overwriting stored output with the most recent output? R 将元素替换为另一个矩阵中具有相应行号的元素 - R replace element with the element that has the corresponding row number in another matrix
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM