【发布时间】:2019-08-03 19:10:05
【问题描述】:
我在 r 中上传了一个大型数据集(简短版本见下文):我想为每个 Cruiseid、Samplenr、Species 和 Age 计算一个值(因此基于四个条件) :
Cruiseid Samplenr Species Age Length LK TNumStat TNumLK
197502 37 154 0 12,5 2 2,791666667 5,583333
197502 37 154 0 17,5 3 2,166666667 6,5
197502 37 154 2 172,5 34 11,54166667 392,4167
197502 37 154 2 177,5 35 12,0625 422,1875
197502 37 154 2 182,5 36 2,083333333 75
197502 35 154 0 112,5 22 11,85654008 260,8439
197502 35 154 2 197,5 39 2,109704641 82,27848
197502 35 154 2 217,5 43 2,109704641 90,7173
197502 35 154 2 232,5 46 2,109704641 97,04641
197502 36 154 0 12,5 2 4,685314685 9,370629
197502 36 154 2 182,5 36 3,496503497 125,8741
197502 41 154 0 17,5 3 2,260869565 6,782609
197502 41 154 2 202,5 40 4,347826087 173,913
197502 41 154 2 212,5 42 2,173913043 91,30435
197502 41 154 2 242,5 48 2,173913043 104,3478
197503 56 154 0 17,5 3 7,428571429 22,28571
197503 56 154 0 147,5 29 10,30952381 298,9762
197503 56 154 2 172,5 34 13,19047619 448,4762
197503 56 154 2 187,5 37 2,380952381 88,09524
197503 54 154 0 12,5 2 3,35 6,7
197503 54 154 0 157,5 31 12 372
197503 54 154 0 167,5 33 13,25 437,25
197503 54 154 2 172,5 34 13,85 470,9
197503 54 154 2 187,5 37 2,5 92,5
197503 54 154 2 217,5 43 2,5 107,5
197503 53 154 0 12,5 2 2,875536481 5,751073
197503 53 154 0 97,5 19 4,806866953 91,33047
197503 53 154 0 107,5 21 5,622317597 118,0687
197503 53 154 0 142,5 28 8,776824034 245,7511
我想计算:((TNumStat$TNumLK/TNumStat$TNumStat)*0.5+0.25)*10for 每个Cruiseid、Samplenr、Species 和Age。
我已经在循环构造中尝试过一些东西:
#######################
Cruise <- unique(TNumStat$Cruiseid)
Track <- unique(TNumStat$Samplenr)
#######################
AvrLengthCr <- c()
AvrLengthCr <- rep(NA, length(TNumStat$Species))
#######################
for(j in 1:length(Cruise)){
t1.ss <- which(TNumStat$Cruiseid == Cruise[j])
###
for(i in 1:length(Track)){
t2.ss <- which(TNumStat$Samplenr[t1.ss] == Track[i])
###
AvrLengthCr[t1.ss][t2.ss] <- ((TNumStat$TNumLK[t1.ss][t2.ss]/TNumStat$TNumStat[t1.ss][t2.ss])*0.5+0.25)*10
}}
但它似乎不起作用。我也一直在用 dcast 研究一些东西:
TNumStat2<-dcast(TNumStat,Cruiseid+Samplenr+Species+Age,formula = (((TNumStat$TNumLK/TNumStat$TNumStat*0.5+0.25)*10) )),na.rm=TRUE)
我尝试过的选项似乎都不起作用,我不知道如何解决这个问题。有人可以帮帮我吗?
谢谢
【问题讨论】:
-
你需要
library(dplyr); df %>% group_by(Cruiseid, Samplenr, Species, Age) %>% mutate(ratio = ((TNumLK/TNumStat)*0.5+0.25)*10)吗? -
您可能必须使用
TNumStat[c("TNumStat", "TNumLK")] <- lapply(TNumStat[c("TNumStat", "TNumLK")], function(x) as.numeric(gsub(",", ".", x)))清理您的数据拳头才能获得真正的小数点和数值。 -
@jay.sf:为什么现在不行呢?现在的数字不正确吗?
标签: r loops aggregate conditional-statements dcast