2017-06-22 31 views
1

我有一个由两列组成的数据集列表类型列表。我想编写一个命令,它将创建第三列,其中包含与所需的第二列字符串对应的值。第二列中所需的字符串是“notGene”。所以如果第二列出现“notGene”,我想让第一列的相应值出现在新生成的第三列中。如果另一列中的值与字符匹配,则创建将新列添加到列表的命令

+1

这将有助于建立一个[最小可重现的例子](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)(一个小的自我容器d代码示例,我们可以根据我们的答案)Thx :-) –

回答

0

我猜你正在寻找的东西是这样的:

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_) 

导致

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

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

$col3 
[1] NA "two" NA 

以上很好的格式化:

> as.data.frame(data) 
    col1      col2 col3 
1 one     hello <NA> 
2 two contains notGene as text two 
3 three     world <NA> 
相关问题