【问题标题】:Create new set of variables equal to the level of a factor in dplyr创建与 dplyr 中因子级别相等的新变量集
【发布时间】:2020-07-23 02:28:26
【问题描述】:

我有一个包含 100 列的 data.frame,遵循约定 wordword_answer

df <- data.frame(apple = "57%", apple_answer = "22%", dog = "82%", dog_answer = "16%")

我这样设置上述两个因子变量的水平:

levels(df$apple) <- c( "66%","57%","48%","39%","30%","22%","12%" )
levels(df$dog) <- c( "82%","71%","60%","49%","38%","27%","16%" )

我正在尝试计算一个距离分数,它是 word 的一个因子的数字级别与其对应的 word_answer. 的数字级别之间的距离

因此,例如,在“apple”答案的情况下,apple 的第一行是“57%”,这是该因素中的第二个因素水平

> which(levels(df$apple) == "57%")
[1] 2

对应的apple_answer 列的因子水平为 6

> which(levels(df$apple) == "22%")
[1] 6

所以在这种情况下,距离得分将是 2-6 = -4

如何计算数据集中每个变量的这些距离分数?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    您可以将数据分为两组,单词及其对应的答案。使用match 获取它们的位置并从每个值中减去并生成新列。

    answer_cols <- grep('_answer', names(df))
    new_cols <- paste0(names(df)[-answer_cols], '_dist')
    
    df[new_cols] <- Map(function(x, y) match(x, levels(x)) - match(y, levels(x)),
                                         df[-answer_cols], df[answer_cols])
    
    df
    #  apple apple_answer dog dog_answer apple_dist dog_dist
    #1   57%          22% 82%        16%         -4       -6
    

    【讨论】:

    • 啊,谢谢!非常令人印象深刻。我花了太多时间试图弄清楚如何在 dplyr 中做到这一点,但这更简单。谢谢!
    【解决方案2】:

    你也可以使用 apply 函数,像这样:

    df$apple_dist = apply(df[,1:2], 1, function(x) {
        which(levels(df$apple) == x[1]) - which(levels(df$apple) == x[2])
    })
    
    df$dog_dist = apply(df[,3:4], 1, function(x) {
        which(levels(df$dog) == x[1]) - which(levels(df$dog) == x[2])
    })
    
    > df
      apple apple_answer dog dog_answer apple_dist dog_dist
    1   57%          22% 82%        16%         -4       -6
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-11
      • 2020-03-07
      • 1970-01-01
      • 2017-08-10
      • 2016-10-13
      • 2021-11-22
      • 1970-01-01
      相关资源
      最近更新 更多