I have a dataframe that looks like this:
df <-
structure(
list(
Exception1 = c(
"Comments from {2}: {0}",
"status updated to {1} by {2}. Description:{0}",
"status updated to {1} by {2}. Description:{0}",
"information only.",
"status updated to {1} by {2}. Description:{0}",
"status updated to {1} by {2}. Description:{0}"
),
Exception2 = c(
"Customer {0} said bla",
"Status updated to {1}",
"Customer said {2}",
"User {0} foo",
"{0} {1}",
"{1} {2}"
),
ARGUMENT1 = c("OK", " ", " ", "PAY9089723089-98391", " ", " "),
ARGUMENT2 = c(
"null",
"Processing",
"Reconciled",
"null",
"Processing",
"Reconciled"
),
ARGUMENT3 = c(
"company name",
"company name",
"company name",
"null",
"company name",
"company name"
)
),
row.names = c(NA, 6L),
class = "data.frame"
)
:
| Exception1 | Exception2 | ARGUMENT1 | ARGUMENT2 | ARGUMENT3 |
|-----------------------------------------------|-----------------------|---------------------|------------|--------------|
| Comments from {2}: {0} | Customer {0} said bla | OK | null | company name |
| status updated to {1} by {2}. Description:{0} | Status updated to {1} | | Processing | company name |
| status updated to {1} by {2}. Description:{0} | Customer said {2} | | Reconciled | company name |
| information only. | User {0} foo | PAY9089723089-98391 | null | null |
| status updated to {1} by {2}. Description:{0} | {0} {1} | | Processing | company name |
| status updated to {1} by {2}. Description:{0} | {1} {2} | | Reconciled | company name |
The Exception1 and Exception 2 columns (there are a couple more Exception columns which I removed for readability) contain placeholders {} that are meant to be replaced with the values in the ARGUMENT* columns.
I have been looking at ways to accomplish this and have been relatively successful but I am still lacking the experience to do it better.
I wrote a simple function that does the replace through gsub:
excp_ren2 <- function(x) {
x %<>%
gsub("\\{1\\}", x["ARGUMENT2"], .) %>%
gsub("\\{0\\}", x["ARGUMENT1"], .) %>%
gsub("\\{2\\}", x["ARGUMENT3"], .)
x
}
And then have been using apply and its variances. I have accomplished for example an OK result with this:
new_df <-
df %>% apply(
.,
MARGIN = 1,
FUN = function(x)
excp_ren2(x)
) %>% as.data.frame()
with the only problem that this transposes the matrix which is not really a problem.
I am looking for better ways to do this, I thought I was going to be able to do this through mutate_* but I think I lose access to the column names for the row inside the function or at least I do not know how to do it. Any ideas on simpler ways to accomplish this?
Thanks!