【发布时间】:2020-03-08 08:58:59
【问题描述】:
我正在为一位同事开展一个项目,以标准化 GC 数据并将从 mol% 转换为 mass%。
编辑:我正在进行逐行标准化。即每次norm1 中的物种总和应该是 100(尽管每个都乘以质量,因此不再总和为 100。在 for 循环中,它相当于一个非常繁重的:
for (time in Nmass[,1]){
for species in norm1{
Nmass[time,species] = Fmolwt[species,] = Nmass[time,species] / rowSums(Nmass[time,norm1])
}
}
我导入了 CSV 文件,它们被排列为物种名称列和注入时间行(处理虚拟数据,因此目前全为零)。
> Nmass[1:5,c("Time",norm1)]
# A tibble: 5 x 13
Time HTFeed_Methane HTFeed_Ethane HTFeed_Ethylene HTFeed_Propane HTFeed_Propylene `HTFeed_iso-butane` `HTFee~ `HTFeed~ `HTFe~ HTFee~ `HTFee~ `HTFee~
<dttm> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 2019-10-06 13:02:00 0 0 0 0 0 0 0 0 0 0 0 0
2 2019-10-06 13:17:00 0 0 0 0 0 0 0 0 0 0 0 0
3 2019-10-06 13:32:00 0 0 0 0 0 0 0 0 0 0 0 0
4 2019-10-06 13:47:00 0 0 0 0 0 0 0 0 0 0 0 0
5 2019-10-06 14:02:00 0 0 0 0 0 0 0 0 0 0 0 0
我有一个正常的正常化例程:
norm1 = c('HTFeed_Methane','HTFeed_Ethane','HTFeed_Ethylene','HTFeed_Propane','HTFeed_Propylene','HTFeed_iso-butane','HTFeed_n-Butane',
'HTFeed_trans-2-butene','HTFeed_1-Butene','HTFeed_Isobutylene','HTFeed_cis-2-butene','HTFeed_1,3-Butadiene')
Nmass[,norm1] = as.data.frame(apply(Nmass[,norm1], 2, function(x) x/sum(x)))
但是当我尝试使用预先构建的物种质量列表来实现质量转换时:
Fmolwt = data.frame(c(16.04,30.07,28.05,44.9,42.08,58.12,58.12,56.11,56.11,56.11,56.11,54.1))
colnames(Fmolwt)[1] = 'weight'
rownames(Fmolwt) = c('HTFeed_Methane','HTFeed_Ethane','HTFeed_Ethylene','HTFeed_Propane','HTFeed_Propylene','HTFeed_iso-butane',
'HTFeed_n-Butane','HTFeed_trans-2-butene','HTFeed_1-Butene','HTFeed_Isobutylene','HTFeed_cis-2-butene','HTFeed_1,3-Butadiene')
套路变成(我认为):
Nmass[,norm1] = as.data.frame(apply(Nmass[,norm1], 2, function(x) x*Fmolwt[x,]/sum(x)))
我收到关于尺寸不同的错误。
Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, :
arguments imply differing number of rows: 0, 3696
In addition: Warning messages:
1: In x * Fmolwt[x, ] :
longer object length is not a multiple of shorter object length
2: In x * Fmolwt[x, ] :
longer object length is not a multiple of shorter object length
3: In x * Fmolwt[x, ] :
longer object length is not a multiple of shorter object length
4: In x * Fmolwt[x, ] :
longer object length is not a multiple of shorter object length
5: In x * Fmolwt[x, ] :
longer object length is not a multiple of shorter object length
6: In x * Fmolwt[x, ] :
longer object length is not a multiple of shorter object length
7: In x * Fmolwt[x, ] :
我预计这是由于 apply 语句试图同时提取 norm1 中命名的所有内容的分子量。
我可以按照我尝试的方式完成这项工作吗,还是我需要编写一个 for 循环?
【问题讨论】:
-
不要使用
apply循环遍历 data.frame 列。使用lapply。无论如何,如果你想同时迭代两个向量/列表/data.frames,你可以使用mapply。 -
@Roland 在这种情况下,您能否为我指出正确的 mapply 方向?
-
嗨@BenA,我查看了您的解释并更正了答案。希望这次是正确的
标签: r