Reputation: 320
I am trying to use grepl() within an if else string within a for loop in order to do something I figure is pretty common in R: I have one column that has long names for plots, and I am trying to take information from that plot column and generate new columns based on that information. For this example, I will provide a version of my data to explain what I have tried:
for(i in seq_along(data)) {
if(grepl("1987", data$id) == TRUE) {
print("dnr87")
} else if { (grepl("1994", data$id) == TRUE) {
else
print("no id")
}
I receive the warning:
the condition has length > 1 and only the first element will be used
My questions are:
Obviously, as seen in the data below, I would like to design the for loop to also go through and assign the same kind of data not only based on a grepl for year, but a grepl for ID (for example, grepl("E14) for the first data point), but I figure if you all can help me with the previous mentioned questions I should be able to incorporate that without huge issues.
Data table (name: data)
id stand plot
E141987 NA NA
E141987 NA NA
E141987 NA NA
E141987 NA NA
E121994 NA NA
E121994 NA NA
E121994 NA NA
E121994 NA NA
E121994 NA NA
E121994 NA NA
E121994 NA NA
E121994 NA NA
W52012 NA NA
W52012 NA NA
W52012 NA NA
W52012 NA NA
W52012 NA NA
W52012 NA NA
Upvotes: 0
Views: 2280
Reputation: 21400
Since you're not providing reproducible data to illustrate the procedure, here's some mock data. If I understand you correctly you want to mutate codes based on patterns. If that's the case you can use nested ifelse statements:
Data:
df <- data.frame(
id = c("a87", "b87", "abc95", "a95", "x123")
)
Now you define the new column with the mutated values:
df$new <- ifelse(grepl("87", df$id), "new1",
ifelse(grepl("95", df$id), "new2", "new3"))
An ifelse
clause takes three arguments as input: (i) the condition, (ii) what to do if the condition holds true, (iii) what to do if it doesn't. The execution of (iii) can be delayed by inserting yet another ifelse
clause testing for a second condition. This in turn can be delayed yet again by a third condition and so on.
The result:
df
id new
1 a87 new1
2 b87 new1
3 abc95 new2
4 a95 new2
5 x123 new3
These are not your data but I guess you get the gist: there's no need for a for
loop and you can nest one ifelse
in another.
Upvotes: 1