Jad*_*ace 0 comparison r dataframe
我有一个包含如下信息的数据框:
df <- data.frame(Col1 = c("value1", "value1", "value2", "value2"), Col2 = c("value2", "value1", "value2", "value1"), stringsAsFactors = F)
+--------+--------+
| Col1 | Col2 |
+--------+--------+
| value1 | value2 |
| value1 | value1 |
| value2 | value2 |
| value2 | value1 |
+--------+--------+
Run Code Online (Sandbox Code Playgroud)
我想创建第三列,其中包含颜色信息,具体取决于前两列的值是否相同。现在我的脚本是这样的:
for (i in 1:nrow(df)) {
if(df[i,1] == df[i,2]) {
df$color[i] <- "black"
} else {
df$color[i] <- "grey"
}
}
Run Code Online (Sandbox Code Playgroud)
这给了我以下输出:
+--------+--------+-------+
| Col1 | Col2 | color |
+--------+--------+-------+
| value1 | value2 | grey |
| value1 | value1 | black |
| value2 | value2 | black |
| value2 | value1 | grey |
+--------+--------+-------+
Run Code Online (Sandbox Code Playgroud)
这是正确的输出,但我想知道是否有更“R”的方法可以做到这一点。我有大量数据,并且 for 循环在这里使用起来不是很快。
小智 5
我认为你可以使用一次来完成此操作ifelse()
df$Col3 = ifelse(df$Col1 == df$Col2, "black", "grey")
Run Code Online (Sandbox Code Playgroud)