[英]for loop with ifelse statement in R
I have a dataset containing as.factor type data for species genus GEN and level of decay DECAY I want to calculate the AGB for every individual row using data from these 2 columns The first set of code only using GEN ran succesfully creating an AGB column storing a AGB value for every specimen.我有一个数据集,其中包含物种属 GEN 的 as.factor 类型数据和衰减水平 DECAY 我想使用来自这 2 列的数据计算每一行的 AGB 仅使用 GEN 的第一组代码成功运行创建 AGB 列存储每个样本的 AGB 值。 The second set of code does not run.
第二组代码没有运行。 I left out the 2 other genus to avoid repetitiveness here.
我省略了另外两个属以避免在这里重复。 The error is pasted at the end.
错误粘贴在最后。 Any tips on why the same approach does not work upon adding a condition.
关于为什么相同的方法在添加条件时不起作用的任何提示。
for (i in 1:nrow(dat)){
if(dat$GEN[i] =='Avicennia'){
dat$AGB[i]<- 140*dat$dbh[i]^2.44
}else if (dat$GEN[i]=='Laguncularia'){
dat$AGB[i]<- 100.23*dat$dbh[i]^2.53
}else if (dat$GEN[i]=='Rhizophora'){
dat$AGB[i]<-128.23*dat$dbh[i]^2.61
}
}
for (i in 1:nrow(dat)){
if(dat$GEN[i] =='Avicennia'& dat$DECAY[i]==0){
dat$AGB[i]<- 0.14*dat$dbh[i]^2.4
}else if (dat$GEN[i]=='Avicennia'& dat$DECAY[i]==0.5){
dat$AGB[i]<- 0.9875*0.14*dat$dbh[i]^2.4
}else if (dat$GEN[i]=='Avicennia' & dat$DECAY[i]==1){
dat$AGB[i]<-0.975*0.14*dat$dbh[i]^2.4
}else if (dat$GEN[i]=='Avicennia'& dat$DECAY[i]==2){
dat$AGB[i]<-0.8*0.14*dat$dbh[i]^2.4
}else if (dat$GEN[i]=='Avicennia'& dat$DECAY[i]==3){
dat$AGB[i]<-0.070*dat$dbh[i]^2.4
}
}
Error in if (dat$GEN[i] == "Avicennia" & dat$DECAY[i] == 0) { :
missing value where TRUE/FALSE needed
If we want to use a compact version, either ifelse
(nested) or a case_when
would be more appropriate如果我们想使用紧凑版本,
ifelse
(嵌套)或case_when
会更合适
library(dplyr)
dat %>%
mutate(AGB = case_when(
GEN == 'Avicennia' & DECAY == 0 & !is.na(DECAY) ~ 0.14* dbh^2.4,
GEN == 'Avicennia' & DECAY == 0.5 & !is.na(DECAY) ~ 0.9875 *0.14* dbh^2.4,
GEN == 'Avicennia' & DECAY == 1 & !is.na(DECAY) ~ 0.975 *0.14* dbh^2.4,
GEN == 'Avicennia' & DECAY == 2 & !is.na(DECAY) ~ 0.8 *0.14* dbh^2.4,
GEN == 'Avicennia' & DECAY == 3 & !is.na(DECAY) ~ 0.07 *0.14* dbh^2.4,
TRUE ~ as.numeric(AGB))
NOTE: There is always a risk involved when we try to compare ( ==
) with a floating value ie 0.5.注意:当我们尝试将 (
==
) 与浮动值(即 0.5)进行比较时,总是存在风险。 Make sure the values are exact and doesn't involve any precision确保值准确且不涉及任何精度
Another option is to use a named vector to match the values in 'DECAY' and then do the calculation based on matching the values另一种选择是使用命名向量来匹配 'DECAY' 中的值,然后根据匹配值进行计算
nm1 <- setNames(c(1, 0.9875, 0.975, 0.8, 0.07), c(0, 0.5, 1, 2, 3))
i1 <- dat$GEN == 'Avicennia'
dat$AGB[i1] <- with(dat, nm1[as.character(DECAY[i1])] * 0.14 * dbh[i1]^2.4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.