R 索引变量缩小到唯一组的数量

R index variable shrunk to number of unique groups

我有一个数据框,dat,有 214 行数据。每行包含这些变量:SpeciesMode redgreen。我按 物种 对数据进行了排序。我想创建一个数字索引变量,如果模式是 red 那么 index = 0 否则 index = 1

此外,索引只能与存在的物种的唯一数量 (N=72) 一样长,这样,如果有 5 个 speciesA,red 和7个种B,绿色是一个红色种,然后是row 1 = 0row 2 = 1等等。这是我到目前为止尝试过的代码:

index <- for (q in 1:unique(species)) {
      ifelse(mode[q]=='red',0,1)
}
index <- as.numeric(factor(my_dataframe$mode))

在幕后,一个因素被存储为一个整数。所以从因子到数值索引的转换是 1 到 1。