[英]Generate new column values based on comparison of two other columns in R
I have a data frame with information like this:我有一个包含以下信息的数据框:
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 |
+--------+--------+
I want to create a third column that has color information depending on if the values of the first two columns are the same or not.我想根据前两列的值是否相同来创建具有颜色信息的第三列。 Right now my script is this:
现在我的脚本是这样的:
for (i in 1:nrow(df)) {
if(df[i,1] == df[i,2]) {
df$color[i] <- "black"
} else {
df$color[i] <- "grey"
}
}
which gives me the following output:这给了我以下 output:
+--------+--------+-------+
| Col1 | Col2 | color |
+--------+--------+-------+
| value1 | value2 | grey |
| value1 | value1 | black |
| value2 | value2 | black |
| value2 | value1 | grey |
+--------+--------+-------+
This is the correct output, but i would like to know if there is a more "R" method of doing this.这是正确的 output,但我想知道是否有更多的“R”方法可以做到这一点。 I have large sets of data and for-loops are not very fast to use here.
我有大量数据,在这里使用 for 循环不是很快。
I think you could do this in one using ifelse()
我认为您可以使用
ifelse()
一次性完成此操作
df$Col3 = ifelse(df$Col1 == df$Col2, "black", "grey")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.