[英]“invalid 'envir' argument of type 'character” when using “with” inside of “apply”
I'm applying two conditions to each row in the dataframe trades1
(basically comparing each row with each other row within one column). 我将两个条件应用于
trades1
每一行(基本上将每一行与一列中的每一行进行比较)。 conditions
vector is supposed to consist of 1 when both conditions are satisfied and 0 otherwise. 当两个条件都满足时,
conditions
向量应该由1组成,否则为0。
Data example: 数据示例:
order date time ms price dir amount hour index i
1 FUT-3 14.02.06 10:00:00.567 1.950535e+16 66.97 BUY 1 5418154 1 1
2 FUT-3 14.02.06 10:00:00.574 1.950535e+16 66.97 BUY 1 5418154 2 2
3 FUT-3 14.02.06 10:00:00.577 1.950535e+16 66.97 BUY 1 5418154 3 3
4 FUT-3 14.02.06 10:00:00.585 1.950535e+16 66.97 BUY 1 5418154 4 4
5 FUT-3 14.02.06 10:00:00.587 1.950535e+16 66.97 BUY 1 5418154 5 5
6 FUT-3 14.02.06 10:00:00.594 1.950535e+16 66.97 BUY 1 5418154 6 6
Code: 码:
conditions <- apply(trades1, 1, function(x) with(x, as.integer(ms - trades$ms == 1e+6 & price/trades1$price >= 1)))
I've checked that trades1
is a dataframe and that columns are numeric. 我检查过
trades1
是一个数据trades1
,并且列是数字。 The error I recieve: 我收到的错误:
Error in eval(substitute(expr), data, enclos = parent.frame()) :
invalid 'envir' argument of type 'character'
In case the problem is not with the data argument, but with placing with
inside of apply
, I'd appreciate suggestions on how to solve this the other way. 如果这个问题是不是与数据的说法,但将
with
内apply
,我会很感激就如何解决这个其他方式的建议。
The first thing that apply
does is convert its argument into a matrix. 第一件事
apply
所做的是转换参数转化为矩阵。 Once that's done, with
doesn't work any more. 完成后,
with
不再起作用。
If you want to loop over rows (are you sure this is the best solution?), use a plain old for
loop, or lapply
over a vector of row numbers: 如果要循环行( 确定这是最好的解决方案?),请使用普通的
for
循环,或lapply
在行号向量上:
lst <- lapply(seq_len(nrow(trades1)), function(row) { with(trades1[row, ], ...) } )
do.call(rbind, lst)
As mentioned by @Hong Ooi apply
converts the dataframe to matrix and hence all your numbers are converted to characters. 如@Hong Ooi所述,
apply
将数据帧转换为矩阵,因此所有数字都转换为字符。 You can correct the apply
loop by doing 您可以通过以下方式更正
apply
循环
apply(df, 1, function(x) as.integer(any(as.numeric(x["ms"]) - df$ms == 1e+6 &
as.numeric(x["price"])/df$price >= 1)))
However, I think a better approach here would be to use mapply
since you want to check the conditions for price
and ms
. 但是,我认为这里最好的方法是使用
mapply
因为您要检查price
和ms
的条件。
as.integer(mapply(function(x, y)
any(x - df$ms == 1e+6 & y/df$price >= 1),df$ms, df$price))
Similar approach using data.table
使用
data.table
类似方法
library(data.table)
setDT(df)[, ans := as.integer(any(ms - df$ms == 1e+6 &
price/df$price >= 1)), by = seq_len(nrow(df))]
and tidyverse
和
tidyverse
library(dplyr)
library(purrr)
df %>%
mutate(ans = map2(ms, price,
~as.integer(any(.x - df$ms == 1e+6 & .y/df$price >= 1))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.