Reputation: 23
`
a <- c("11-12", "22-22", "11-33")
b <- c("33-22", "33-22", "44-33")
c <- c("15-66", "33-54", "22-66")
df <- data.frame(a,b,c)
Hi I have a dataframe like this and want to compare the three columns using specific substring along the rows and give me a new column with the logical answer as 1 or zero for specific substring. Meaning it should first see in the first column first row "11", then in second column first row "33" and then third column "66". if it satisfies all the three column it should give result as 1 in new column, later it should do it for all the rows.
the new column result should be like 1, 0,1
Kindly let me know if any one has answer for this, thank you very much.
Upvotes: 0
Views: 122
Reputation: 3240
Straightforward using data.table
.
library(data.table)
a <- c("11-12", "22-22", "11-33")
b <- c("33-22", "33-22", "44-33")
c <- c("15-66", "33-54", "22-66")
dat <- data.table(a,b,c)
dat[, newcol := 0]
dat[a %like% "11" & b %like% "33" & c %like% "66", newcol := 1]
# a b c newcol
# 1: 11-12 33-22 15-66 1
# 2: 22-22 33-22 33-54 0
# 3: 11-33 44-33 22-66 1
Upvotes: 1
Reputation: 887421
We can try
as.integer(apply(df, 1, FUN = function(x) grepl("11", x[1]) &
grepl("33", x[2]) & grepl("66", x[3])))
#[1] 1 0 1
Or with Reduce
and Map
as.integer(Reduce(`&`, Map(grepl, c(11, 33, 66), df)))
#[1] 1 0 1
Upvotes: 0