【问题标题】:R: Loop over several column to compare variables [duplicate]R:循环几列以比较变量[重复]
【发布时间】:2021-03-22 15:40:15
【问题描述】:

我想遍历几列以比较数据框中的这些变量。

例如:

df1
| col1     | col2  | col3  |
| -------- | ------|-------|
| First    | PwC   | PwC   |
| Second   | BCG   | BCG   |
| Third    | web   | txt   |

看看那个例子,我想循环 col2 和 col3。

如果 df1[1,2] == df1[1,3],则在新的 col4 中写入 0,否则在 col4 中写入 1。

有人有想法吗?

提前致谢!

【问题讨论】:

  • df1$col4<-ifelse(df1$col2 == df1$col3, 1, 0) 应该可以工作

标签: r


【解决方案1】:

我们不需要循环。只需创建一个逻辑向量并将其强制转换为二进制 (as.integer)

df1$col4 <- as.integer(df1$col2 != df1$col3)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 2021-12-09
    相关资源
    最近更新 更多