【问题标题】:conditional elseif statements in RR中的条件elseif语句
【发布时间】:2015-09-12 12:43:55
【问题描述】:

我有一个看起来像这样的数据框

Animal
species sum
A       2
A       6
B       8
B       1
C       6
C       3
D       5
D       4

我想要将每个物种的最小总和除以最大总和并创建一个名为比率的新列的代码,如果该数字大于 .2,我希望它返回该比率,但如果它小于.2,我希望它返回 NA。 我想在 dplyr 中执行此操作 这是我目前拥有的代码,但它不起作用 我在 R

中有这串命令
animal <- animal %>% 
+     group_by(species) %>% 
+     mutate(ratio = ifelse((min(sum)/max(sum) > .2), (min(sum)/max(sum)), "NA"))

谢谢!

最后应该是这个样子

species sum   ratio
A       2   .333
A       6   .333
B       8    NA
B       1    NA
C       6    .5
C       3    .5
D       5    .8
D       4    .8

【问题讨论】:

  • 您使用的是字符串“NA”而不是真正的 NA。如果您想稍后对数据集进行子集化,最好使用与is.na 和其他功能一起使用的真实 NA

标签: r if-statement conditional dplyr


【解决方案1】:

我会避免使用ifelse,因为无论如何您都必须评估整个向量,并且因为您需要计算整个过程两次。以下是我的做法

library(data.table)
setDT(Animal)[, ratio := {r <- range(sum); r[1L]/r[2L]}, by = species]
Animal[ratio <= .2, ratio := NA]
#    species sum     ratio
# 1:       A   2 0.3333333
# 2:       A   6 0.3333333
# 3:       B   8        NA
# 4:       B   1        NA
# 5:       C   6 0.5000000
# 6:       C   3 0.5000000
# 7:       D   5 0.8000000
# 8:       D   4 0.8000000

【讨论】:

    【解决方案2】:
        animal <- animal %>% 
                group_by(species) %>% 
                 mutate(ratio = ifelse((min(sum)/max(sum) > .2), (min(sum)/max(sum)), as.numeric(NA)))
    
    > animal
    Source: local data frame [8 x 3]
    Groups: species
    
      species sum     ratio
    1       A   2 0.3333333
    2       A   6 0.3333333
    3       B   8        NA
    4       B   1        NA
    5       C   6 0.5000000
    6       C   3 0.5000000
    7       D   5 0.8000000
    8       D   4 0.8000000
    

    【讨论】:

      【解决方案3】:

      您可以使用NA_real_ 使类型兼容

       animal %>% 
        group_by(species) %>% 
        mutate(ratio= ifelse((min(sum)/max(sum))> .2,
            round((min(sum)/max(sum)),2), NA_real_))
      #  species sum ratio
      #1       A   2  0.33
      #2       A   6  0.33
      #3       B   8    NA
      #4       B   1    NA
      #5       C   6  0.50
      #6       C   3  0.50
      #7       D   5  0.80
      #8       D   4  0.80
      

      基本的 R 选项是

      animal$ratio <-  with(animal, ave(sum, species, FUN=function(x) {
                        x1 <- min(x)/max(x)
                        NA^(x1 <= 0.2)*x1 }))
      

      【讨论】:

        猜你喜欢
        • 2020-07-18
        • 1970-01-01
        • 2014-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多