首页 > 解决方案 > 在 R 中创建一个新的 cloumn

问题描述

我想在 r 数据框中创建一个新列。我想将其他列中的此列值作为此示例:

ID  column1 column2 
1    C       C
2    B       C
3    A       A
4    C       B

新列应在 2 列中包含任何可用的 C,并且其值应如下所示:

ID  column1 column2  new column
1    C       C        Present
2    B       C        Present 
3    A       A        Absent
4    C       B        Present

因为我只想要列中的 C 你能帮帮我吗?

标签: r

解决方案


这也可以在基础 R 中使用:

DF$new_column <- Map(function(x, y) c("Absent", "Present")[any("C" %in% c(x, y)) + 1], 
                     DF$column1, DF$column2)
DF

  ID column1 column2 new_column
1  1       C       C    Present
2  2       B       C    Present
3  3       A       A     Absent
4  4       C       B    Present

推荐阅读