Monica Heddneck
Monica Heddneck

Reputation: 3125

ifelse and %in% applied to rows of a dataframe in R

Excuse my simple question, but since ifelse is vectorized, shouldn't it iterate through the rows of my dataframe?

e.g, when I try

   df <- data.frame(col1=c("a", "b", "c"),
                    col2=c("d", "e", "f"), 
                    col3=c("g", "h", "i"), stringsAsFactors=FALSE)

    ifelse('a' %in% df, 1, 0)

My result is 0.

Shouldn't it be 1, 0, 0?

In this case, what's the point of ifelse? Can I somehow use this function to iterate through my dataframe?

Upvotes: 2

Views: 1392

Answers (1)

blep
blep

Reputation: 726

If you are attempting to iterate over rows, rather than columns:

apply(df,1, function(y){ ifelse('a' %in% y, 1, 0)})

If you are iterating over columns, then lapply will work:

lapply(df, function(y){ ifelse('a' %in% y, 1, 0)})

(The difference will be more obvious if you are looking for an element that doesn't have the same row-index and column-index in your data frame.)

Upvotes: 2

Related Questions