Reputation: 95
I have two variable a and b
A B
1 id
-1 asddnewid
13 asddsatransID
-1 sadsddsdasd
-1 asdsadasdd
I want to find if a is > 0 then i want to search the variable B for character "transid" and get the index of it.
I tried the below code
if (a > 0) {
c = regexpr("transid=",B)
}
But it showing error. I am not sure whether iam writing the if condition properly
Upvotes: 1
Views: 86
Reputation: 886938
We can use grep
. If we need the index from only the positive values in "A"
grep("transID", df1$B[df1$A>0])
#[1] 2
If the index is based on all the rows
i1 <- which(df1$A >0 & grepl("transID", df1$B))
i1
#[1] 3
sapply(gregexpr("transID", df1$B[i1]), c)
#[1] 7
Or just
r1 <- sapply(gregexpr("transID", df1$B[df1$A > 0]), c)
r1[r1 >0]
#[1] 7
Regarding using if
condition, if
is not vectorized, so it may be good to use ifelse
. However, from the OP's post, the a
is not defined. I am assuming that the OP meant A
.
df1 <- structure(list(A = c(1L, -1L, 13L, -1L, -1L), B =
c("id", "asddnewid",
"asddsatransID", "sadsddsdasd", "asdsadasdd")), .Names = c("A",
"B"), class = "data.frame", row.names = c(NA, -5L))
Upvotes: 1