Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R中的数据帧到矩阵_R_Matrix_Dataframe - Fatal编程技术网

R中的数据帧到矩阵

R中的数据帧到矩阵,r,matrix,dataframe,R,Matrix,Dataframe,在R中,我使用for循环迭代一个大数据帧,试图将第*I*th行第7列中的整数放入另一个矩阵中的特定索引中。特定索引对应于大数据帧中的索引(同样在*i*th行中,但在第2列和第4列中)。例如,假设我的数据帧具有data_frame[1,2]=5、data_frame[1,4]=12和data_frame[1,7]=375。我想把375放入索引中的矩阵中,其中行的名称为5,列的名称为12 然而,问题是(我认为)当我做col_index=which(colnames(matrix)=data_fram

在R中,我使用for循环迭代一个大数据帧,试图将第*I*th行第7列中的整数放入另一个矩阵中的特定索引中。特定索引对应于大数据帧中的索引(同样在*i*th行中,但在第2列和第4列中)。例如,假设我的数据帧具有data_frame[1,2]=5、data_frame[1,4]=12和data_frame[1,7]=375。我想把375放入索引中的矩阵中,其中行的名称为5,列的名称为12

然而,问题是(我认为)当我做col_index=which(colnames(matrix)=data_frame[1,2])时,它返回整数0。从技术上讲,列名是5,但我注意到只有当我使用col_index=which(colnames(matrix)=“5”)时,它才起作用。如何确保(在for循环中)data_frame[I,2]对应于“5”

数据保存为“out”我想将数据放入的矩阵称为“m”

接下来,第3列等于27的条件

for(i in 8:2446)
{
if(out[i,3]==27)
{
out_col=out[i,4]
out_row=out[i,2]
moves=out[i,7]
col_index=which(colnames(m)==paste(out_col))
row_index=which(rownames(m)==paste(out_row))
m[row_index,col_index]=moves
}
}

很抱歉缺少格式。这是在矩阵中输入数字,但它们不是正确的数字,我也不知道出了什么问题。任何帮助都将不胜感激

您的示例有很多复杂性,但归根结底是替换
mat
中的值,其中行名、列名和新值存储在
out
中。让我们从一个可复制的示例开始(如果您发布了一个示例,它会很有帮助!)

#要替换值的矩阵
垫子
for(i in 8:2446)
{
if(out[i,3]==27)
{
out_col=out[i,4]
out_row=out[i,2]
moves=out[i,7]
col_index=which(colnames(m)==paste(out_col))
row_index=which(rownames(m)==paste(out_row))
m[row_index,col_index]=moves
}
}
# Matrix to have values replaced
mat <- matrix(0, nrow=3, ncol=3)
rownames(mat) <- c("1", "2", "3")
colnames(mat) <- c("4", "5", "6")
mat
#   4 5 6
# 1 0 0 0
# 2 0 0 0
# 3 0 0 0

out <- data.frame(row=c(1, 3, 3), col=c(6, 5, 4), val=c(1, 4, -1))
out
#   row col val
# 1   1   6   1
# 2   3   5   4
# 3   3   4  -1
mat[cbind(as.character(out$row), as.character(out$col))] <- out$val
mat
#    4 5 6
# 1  0 0 1
# 2  0 0 0
# 3 -1 4 0