I Have two data frames df, df2 . df have the column “regular_ex” where i have regular expression of all the variables in df2$col .
i want to join all the variables from df2 with the help of column regular_ex in df
df <- data.frame(var = c("D52", "D31", "D32", "D33", "D34_1"),
regular_ex = c("^D52_","^D31_\d_1$", "^D32_", "^D33_", "^D34_\d_1$"),
dt = c("STA", "MP", "ST", "LI", "DA"))
df2 <- data.frame(col = c("D52_1", "D3_1_1", "D32_1", "D33_1", "D34_1"),
city = c("Munich","Ceylon", "Dhaka", "London", "NY"),
rev = c(1653,1432,7642,9864,6522))
df$col <- NA
df$city <- NA
df$rev <- NA
for (i in 1:nrow(df)) {
regular_exp <- df$regular_ex[i]
matching_variables <- grep(regular_exp, df2$col, value = TRUE)
if (length(matching_variables) > 0) {
matched_index <- match(matching_variables[1], df2$col)
df$col[i] <- df$col[matched_index]
df$city[i] <- df$city[matched_index]
}
}
New contributor
Rcoder1 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.