1

I have a dataset of type list consisting of two columns. I want to write a command that will create a third column consisting of values that correspond to a desired string of column two. The desired string from column two is "notGene". So if "notGene" appears in column two, I want its corresponding value in column one to appear in the newly generated column three.

Mike Rett
  • 19
  • 2
  • 1
    It would be helpful to create a [minimum reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) (a small self-contained code example we can base our answer on) Thx :-) – R Yoda Jun 22 '17 at 21:26

1 Answers1

0

I guess you are looking for something like this:

data <- list(col1 = c("one", "two", "three"),
             col2 = c("hello", "contains notGene as text", "world"))
data$col3 = ifelse(grepl("notGene", data$col2, fixed = TRUE),
                   data$col1, NA_character_)

which results in

> data
$col1
[1] "one"   "two"   "three"

$col2
[1] "hello"                    "contains notGene as text"
[3] "world"                   

$col3
[1] NA    "two" NA   

or more nicely formatted:

> as.data.frame(data)
   col1                     col2 col3
1   one                    hello <NA>
2   two contains notGene as text  two
3 three                    world <NA>
R Yoda
  • 8,358
  • 2
  • 50
  • 87