timw
timw

Reputation: 13

Expand data frame from row vectors

I am trying to add boolean columns to my data frame, then do a summary based on those values. Seems very simple.

The logic is based on search strings within the existing columns. So I thought I'd first create vectors using grep, identifying my "good" rows...

v1<-grep("bingo",df$col1)
v2<-grep("bingo",df$col2)

> head(v1)
[1]   64  741 1657 1905 2010 4116
> head(v2)
[1]  28  68 181 191 296 667

Then I thought I could use some kind of merge/bind/transform function to append columns to the original data frame.

df$add1<-cbind(df,v1)
df$add2<-cbind(df,v2)

But that didn't work due to "arguments imply differing number of rows"

Any idea how to do this?

Upvotes: 1

Views: 388

Answers (2)

Henry
Henry

Reputation: 6784

You might find grepl (logical grep) easier to use:

df$v1 <- grepl("bingo",df$col1)
df$v2 <- grepl("bingo",df$col2)

Upvotes: 3

alexwhan
alexwhan

Reputation: 16026

If v1 is rows that should be TRUE, you could:

df$bingo <- FALSE
df$bingo[v1] <- TRUE

Upvotes: 1

Related Questions