【问题标题】:Reference column by column index逐列索引参考
【发布时间】:2020-11-22 20:53:26
【问题描述】:

有一个像虹膜这样的数据集,任何帮助将不胜感激,

iris %>% head %>% mutate(sum = .[[1]] + .[[2]]) #works

iris %>% head %>% mutate(max = max(.[1], .[2])) #doesnt work

期待答案,找max(1st column, 2nd column)

 Sepal.Length Sepal.Width Petal.Length Petal.Width Species max
1          5.1         3.5          1.4         0.2  setosa 5.1
2          4.9         3.0          1.4         0.2  setosa 4.9
3          4.7         3.2          1.3         0.2  setosa 4.7
4          4.6         3.1          1.5         0.2  setosa 4.6
5          5.0         3.6          1.4         0.2  setosa 5.0
6          5.4         3.9          1.7         0.4  setosa 5.4

提前多谢

【问题讨论】:

    标签: r dplyr tidyr data-manipulation


    【解决方案1】:

    我们需要元素最大值,这可以通过pmax 来实现

    iris %>%
        head %>%
        mutate(max= pmax(.[[1]] , .[[2]]) )
    

    max 的问题在于它的用法是

    max(..., na.rm = FALSE)

    这里,... 表示

    数字或字符参数

    因此,它采用传递给函数的所有列的max 值,而不是列的元素最大值

    + 是一个不同的函数,它始终是元素级的,但是如果我们执行 sum(这将是与 max 进行检查的对应候选对象),它也执行与 max 相同的行为

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-06
      • 2018-03-23
      • 2013-07-06
      • 2020-05-14
      • 2021-09-23
      • 2017-03-27
      相关资源
      最近更新 更多