0

I need assistance with identifying an effective approach in R for conditionally assigning values to a new column in a data matrix after testing to see if specific string exist in two columns. I am using R Studio for these manipulations (I would characterize my skills with R under the "working knowledge" thereof).

I experimented with an admittedly verbose series of if() else() statements with each containing two conditions. Unfortunately, the result in R Studio is "There were [x number] of warnings (use warnings()..." or "...the condition has length > 1 and only the first element will be used." I couldn't find a solution on my own (or after reading various forum posts that expressed similar issues).

My data matrix looks something like this in the R Studio console:

enter image description here

I want to add a new example column called "Tag" and so I tried something like the following:

>exampleTable["Tag"] <- if(exampleTable$Subject == "Subject 1" & exampleTable$Author = "Eminem"){"Tag 1"} else if (exampleTable$Subject == "Subject 1" & exampleTable$Author = "Freddie Mac"){"Tag 2"}

Ideally, a working solution would successfully test for the existence of specific string in the "Subject" and "Author" columns and the result would be the new "Tag" column with whatever new string we wanted to add such as "Tag 1", "Tag 2", etc.

I understand the example above doesn't work so what is a better approach to do this? Thanks!

wyattburp86
  • 51
  • 1
  • 8
  • 2
    Did you try `ifelse`? – coffeinjunky May 07 '19 at 22:00
  • 1
    `if` takes exactly one logical (i.e., length 1), so `&` should not be used (though is identical if both sides are length-1). Perhaps you mean `ifelse` in your vectorized conditional? – r2evans May 07 '19 at 22:00
  • Please provide data as plain text, not images, so users can copy/paste in their answers: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – neilfws May 07 '19 at 22:04
  • In the future, providing a *reproducible* example is encouraged. To do so, please provide usable and unambiguous data; in this case, your data is a JPG, suggesting that if we want to try using your data, we need to transcribe it manually (in general, it is unlikely to happen). For unambiguous data, try `dput(head(x))`. Please also include your expected output. Refs: https://stackoverflow.com/questions/5963269, https://stackoverflow.com/help/mcve, and https://stackoverflow.com/tags/r/info. – r2evans May 07 '19 at 22:04
  • Thanks, all for the pointers. I was able to re-work my series of if else statements into a couple of ifelse() statements and got the desired result. Cheers! – wyattburp86 May 07 '19 at 22:46

1 Answers1

0

Per comments from r2evans and coffeinjunky, ifelse() yielded the results I needed.

wyattburp86
  • 51
  • 1
  • 8