【问题标题】:R index variable shrunk to number of unique groupsR索引变量缩小到唯一组的数量
【发布时间】:2017-04-04 19:38:26
【问题描述】:

我有一个数据框,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)
}

【问题讨论】:

  • 感谢所有通过 pm 帮助我的人。

标签: r indexing shrink


【解决方案1】:
index <- as.numeric(factor(my_dataframe$mode))

在底层,因子存储为整数。所以从因子到数字索引的转换是1到1。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    相关资源
    最近更新 更多