1
我有一個由兩列組成的數據集列表類型列表。我想編寫一個命令,它將創建第三列,其中包含與所需的第二列字符串對應的值。第二列中所需的字符串是「notGene」。所以如果第二列出現「notGene」,我想讓第一列的相應值出現在新生成的第三列中。如果另一列中的值與字符匹配,則創建將新列添加到列表的命令
我有一個由兩列組成的數據集列表類型列表。我想編寫一個命令,它將創建第三列,其中包含與所需的第二列字符串對應的值。第二列中所需的字符串是「notGene」。所以如果第二列出現「notGene」,我想讓第一列的相應值出現在新生成的第三列中。如果另一列中的值與字符匹配,則創建將新列添加到列表的命令
我猜你正在尋找的東西是這樣的:
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>
這將有助於建立一個[最小可重現的例子](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)(一個小的自我容器d代碼示例,我們可以根據我們的答案)Thx :-) –