Error in for loop and IF function

Dear community,

I have a simple vector
my_coins <- c("eth","usdt","link","doge")

I'm trying to calculate a for-loop in combination with an if-statement :

for(i in 1:length(mdata$symbol)) {
if(mdata$symbol[i] == "eth" || "usdt" || "link" || "dodge"){


but I keep getting the an error stating: Error in mdata$symbol[i] == "eth" || "usdt" :
invalid 'y' type in 'x || y'

Can someone please help me to fix this error?

If you want to evaluate if something appears within a vector or list of things, use the %in% operator.
Also r is a vectorised language , so the sort of code you are writing does not require for loops generally.
It seems you are using data.frames, learning tidyverse will likely bring you huge benefits.

1 Like


See the FAQ: How to do a minimal reproducible example reprex for beginners; don't make reverse-engineering data objects an obstacle to attracting questions.

The immediate problem is that logical operators (see help(logic)

These operators act on raw, logical and number-like vectors

As @nirgrahamuk notes, vectorizing in dplyr is more fluid and succinct. It also returns a more useful object.

In using a for loop, seq_along is preferred over length and providing a "receiver" object avoids the surprise of receiving only the last value of [i].

my_coins <- c("eth","usdt","link","doge") 

mdata <- data.frame(symbol = c("usdt","doge"), current_price = c(1,2))
#>   symbol current_price
#> 1   usdt             1
#> 2   doge             2

result <- list()

for(i in seq_along(mdata)) 
  if (mdata$symbol[i] %in% my_coins) result[i] = mdata$current_price[i]

#> [1] 1 2


mdata %>% filter(symbol %in% my_coins)
#>   symbol current_price
#> 1   usdt             1
#> 2   doge             2