Concisely adding values in a loop to a column In my data frame I assign values to the column Register by checking another column (Source) for specific values. Based on those values, the output in Register changes.

I am relatively new to R, but I have some coding knowledge. The following code contains lines that are all so similar that I can't help but wonder if it can't be done way simpler with a condition. In JavaScript, for instance, I'd do this with a case-function. I do not know, however, if something similar is possible in R.

d$Register &lt;- "Banana placeholder"
d$Register[grep(".*/comp-a/.*", d$Source, perl=TRUE)] &lt;- "a: spont-conv"
d$Register[grep(".*/comp-b/.*", d$Source, perl=TRUE)] &lt;- "b: interv-ler-nl"
d$Register[grep(".*/comp-(c|d)/.*", d$Source, perl=TRUE)] &lt;- "c/d: telefoon"
d$Register[grep(".*/comp-e/.*", d$Source, perl=TRUE)] &lt;- "e: onderhandeling"
d$Register[grep(".*/comp-f/.*", d$Source, perl=TRUE)] &lt;- "f: interv-radio-tv"
d$Register[grep(".*/comp-g/.*", d$Source, perl=TRUE)] &lt;- "g: debat"
d$Register[grep(".*/comp-h/.*", d$Source, perl=TRUE)] &lt;- "h: les"
d$Register[grep(".*/comp-i/.*", d$Source, perl=TRUE)] &lt;- "i: spont-comm-radio-tv"
d$Register[grep(".*/comp-j/.*", d$Source, perl=TRUE)] &lt;- "j: reportage-radio-tv"
d$Register[grep(".*/comp-k/.*", d$Source, perl=TRUE)] &lt;- "k: nieuws-radio-tv"
d$Register[grep(".*/comp-l/.*", d$Source, perl=TRUE)] &lt;- "l: comm-radio-tv"
d$Register[grep(".*/comp-m/.*", d$Source, perl=TRUE)] &lt;- "m: misviering"
d$Register[grep(".*/comp-n/.*", d$Source, perl=TRUE)] &lt;- "n: college"
d$Register[grep(".*/comp-o/.*", d$Source, perl=TRUE)] &lt;- "o: voorgelezen"
It would be better to make a list of the parameters, 
and then use a loop to perform the assignments.
That will reduce the duplication of logic,
for example in the long grep(...).

params &lt;- list(
  c("/comp-a/", "a: spont-conv"),
  c("/comp-b/", "b: interv-ler-nl"),
  c("/comp-(c|d)/", "c/d: telefoon"),
  c("/comp-e/", "e: onderhandeling"),
  c("/comp-f/", "f: interv-radio-tv"),
  c("/comp-g/", "g: debat"),
  c("/comp-h/", "h: les"),
  c("/comp-i/", "i: spont-comm-radio-tv"),
  c("/comp-j/", "j: reportage-radio-tv"),
  c("/comp-k/", "k: nieuws-radio-tv"),
  c("/comp-l/", "l: comm-radio-tv"),
  c("/comp-m/", "m: misviering"),
  c("/comp-n/", "n: college"),
  c("/comp-o/", "o: voorgelezen")
)

placeholder &lt;- "PLACEHOLDER"
d$Register &lt;- placeholder

for (i in 1:length(params)) {
  pattern.i &lt;- params[[i]][1]
  label.i &lt;- params[[i]][2]
  d$Register[grep(pattern.i, d$Source)] &lt;- label.i
}

if (nrow(d[d$Register == placeholder]) &gt; 0) stop('Register is not assigned in some rows')


Some other minor improvements:


Simplified the regular expressions: pattern will match the same things as .*pattern.*
No need for the perl = T parameter in grep