我想在R中使用for循环构建一个具有特定值的矩阵。
列名:unique(flowdata$name)
行名:unique(flowdata$attrs[which(flowdata$metadata=='name')])
值: outputGroup 0和2的 meanValue 。*
下面是我的代码,但是当我运行它时,我收到错误说
Error in `[<-`(`*tmp*`, row.name, col.name, value = 6876) :
subscript out of bounds
我要创建的基质:对于第一列“乙酸,在植物中”,它应该返回“1”表示“乙酸,植物(第1行)”和“0.18841”表示“回收的能量,在乙酸生产(第2行)“。
以下是我缩短的示例数据:https://www.dropbox.com/s/10it07wqzfwctd6/Data_Sample.txt?dl=0
n.up = length(unique(flowdata$name)) # number of unit processes
n.p = length(unique(flowdata$attrs[which(flowdata$metadata=='name')]))
#number of inputs/outputs
output.mat <- matrix(0,n.p,n.up) #empty matrix
colnames(output.mat) <- unique(flowdata$name) # up names
rownames(output.mat) <-
unique(flowdata$attrs[which(flowdata$metadata=='name')])
# inputs/outputs names
# check output.mat size
data <- flowdata
for (i in 1:nrow(data)){ # for every row in data
if ((data$metadata[i]=='outputGroup' && data$attrs[i] == 0) ||
(data$metadata[i]=='outputGroup' && data$attrs[i] == 2)){ # if it is an
#output and it is a reference product or a co-product
col.name <- data$name[i] # up name
row.name <- data$attrs[i-4] # i/o name
value <- as.numeric(data$attrs[i-5]) #value
output.mat[row.name,col.name] <- value
}
}
output.mat <- output.mat[-which(rowSums(output.mat)==0),] # if the row is
#empty, then the flow was an input or output of no interest
答案 0 :(得分:0)
output.mat返回值&lt;&gt; 0.您的代码不会像您提供的那样运行;然而。在某些地方,您说您的数据存储在'flowdata'中,而在'data'中存储在其他位置。以下是快速解决方法。
n.up = length(unique(flowdata$name)) # number of unit processes
n.p = length(unique(flowdata$attrs[which(flowdata$metadata=='name')]))
#number of inputs/outputs
output.mat <- matrix(0,n.p,n.up) #empty matrix
colnames(output.mat) <- unique(flowdata$name) # up names
rownames(output.mat) <-
unique(flowdata$attrs[which(flowdata$metadata=='name')])
# inputs/outputs names
# check output.mat size
data <- flowdata
for (i in 1:nrow(data)){ # for every row in data
if ((data$metadata[i]=='outputGroup' && data$attrs[i] == 0) ||
(data$metadata[i]=='outputGroup' && data$attrs[i] == 2)){ # if it is an
#output and it is a reference product or a co-product
col.name <- data$name[i] # up name
row.name <- data$attrs[i-4] # i/o name
value <- as.numeric(data$attrs[i-5]) #value
output.mat[row.name,col.name] <- value
}
}
output.mat <- output.mat[-which(rowSums(output.mat)==0),] # if the row is empty, then the flow was an input or output of no interest
print(output.mat)
输出如下:
Acetic acid, at plant
Acetic acid, at plant 1.00000
Recovered energy, at acetic acid production 0.18841
Acrylonitrile, at plant 0.00000
Recovered energy, for acrylonitrile 0.00000
Acrylonitrile, at plant
Acetic acid, at plant 0.0000000
Recovered energy, at acetic acid production 0.0000000
Acrylonitrile, at plant 1.0000000
Recovered energy, for acrylonitrile 0.0051834