data.table ifelse 行为存在问题
我正在尝试使用 data.table 计算一个简单的比率。不同的文件有不同的 tmax 值,这就是我需要 ifelse
的原因。当我调试这个时,dt 看起来不错。 tmaxValue
是单个值(本例中遇到的第一个“t=60”),但 t0Value
是 dt 中的所有“t=0”值。
summaryDT <- calculate_Ratio(reviewDT[,list(Result, Time), by=key(reviewDT)])
calculate_Ratio <- function(dt){
tmaxValue <- ifelse(grepl("hhep", inFile, ignore.case = TRUE),
dt[which(dt[,Time] == "t=240min"),Result],
ifelse(grepl("hlm",inFile, ignore.case = TRUE),
dt[which(dt[,Time] == "t=60"),Result],
dt[which(dt[,Time] == "t=30"),Result]))
t0Value <- dt[which(dt[,Time] == "t=0"),Result]
return(dt[,Ratio:=tmaxValue/t0Value])
}
我得到的是 tmaxValue
的 Result
除以所有 t0Value
的所有 Result
> 的,但我想要的是每个唯一的 by
的单一比率。
感谢您的帮助。
I am trying to calculate a simple ratio using data.table. Different files have different tmax values, so that is why I need ifelse
. When I debug this, the dt looks good. The tmaxValue
is a single value (the first "t=60" encountered in this case), but t0Value
is all of the "t=0" values in dt.
summaryDT <- calculate_Ratio(reviewDT[,list(Result, Time), by=key(reviewDT)])
calculate_Ratio <- function(dt){
tmaxValue <- ifelse(grepl("hhep", inFile, ignore.case = TRUE),
dt[which(dt[,Time] == "t=240min"),Result],
ifelse(grepl("hlm",inFile, ignore.case = TRUE),
dt[which(dt[,Time] == "t=60"),Result],
dt[which(dt[,Time] == "t=30"),Result]))
t0Value <- dt[which(dt[,Time] == "t=0"),Result]
return(dt[,Ratio:=tmaxValue/t0Value])
}
What I am getting out is theResult
for tmaxValue
divided by all of the Result
's for all of the t0Value
's, but what I want is a single ratio for each unique by
.
Thanks for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有提供可重现的示例,但通常使用
ifelse
是错误的做法。尝试使用
if(...) ... else ...
代替。ifelse(test, yes, no)
的行为非常奇怪:它生成的结果具有来自test
属性和长度 > 以及yes
或no
的值。...所以在你的情况下,你应该得到一些没有属性且长度为一的东西 - 这可能不是你想要的,对吧?
[更新] ...嗯,或者也许是因为您说 tmaxValue 是单个值...
那么问题不在于计算
tmaxValue
吗?请注意,ifelse
仍然是一个错误的工具......You didn't provide a reproducible example, but typically using
ifelse
is the wrong thing to do.Try using
if(...) ... else ...
instead.ifelse(test, yes, no)
acts very weird: It produces a result with the attributes and length fromtest
and the values fromyes
orno
....so in your case you should get something without attributes and of length one - and that's probably not what you wanted, right?
[UPDATE] ...Hmm or maybe it is since you say that
tmaxValue
is a single value...Then the problem isn't in calculating
tmaxValue
? Note thatifelse
is still the wrong tool for the job...