PSraj PSraj - 27 days ago 8
R Question

Pattern generation based on data frame in R

I am looking to generate a pattern based on some columns of a data frame.
Sample data set could be :

domain <- c('ebay.com','facebook.com','auto.com')
id <- c(21000, 23400, 26800)
cost <- c(0.82,0.40,0.57)
rand_val <- c(0000807,0000808,0000809)
test_data <- data.frame(domain,id,cost,rand_val)


Based on COLUMNS of test_data i am looking to generate this pattern as text output:

if every domain = "ebay.com", id in (21000):
rand_val:0000807
cost: 0.82
elif every domain = "facebook.com", id in (23400):
rand_val:0000808
cost: 0.40
elif every domain = "auto.com", id in (26800):
rand_val:0000809
cost: 0.57


How can i iterate based on number of rows in the data frame to produce this pattern.

Answer

You can use paste with sep and collapse for this:

res <- paste('if every domain = "',test_data$domain, '", id in (', test_data$id, '):
  rand_val:', test_data$rand_val, '
cost: ', test_data$cost, sep="", collapse = "
el")
cat(res)

if every domain = "ebay.com", id in (21000):
  rand_val:807
cost: 0.82
elif every domain = "facebook.com", id in (23400):
  rand_val:808
cost: 0.4
elif every domain = "auto.com", id in (26800):
  rand_val:809
cost: 0.57
Comments