使用R语言将奇偶数分开并将结果放置在两个单独的向量中

时间:2019-05-16 04:10:46

标签: r

如何隔离向量中存在的奇偶数。 我简化了 R语言的功能,以帮助初学者。

    numbers <- list(2,5,8,9,14,20) #List containing even odd numbers
    en<-list()                     #Initiating even numbers’ list
    on<-list()                     #Initiating odd numbers’ list

    #Function creation

    sep <- function(x){
    for (i in x)
    {

    ifelse((i%%2)==0, en <- paste(append(en,i, length(en)+1), collapse = ","),
                      on <- paste(append(on,i, length(on)+1), collapse = ","))
    }
  message("Even numbers are : ", unlist(en)) #Unlist is to convert list into vector
  message("Odd numbers are : ", unlist(on))  #Unlist is to convert list into vector
    }

    #Passing the function with argument

    sep(numbers)

**Result!**
Even numbers are : 2,8,14,20

Odd numbers are : 5,9

1 个答案:

答案 0 :(得分:0)

通过逻辑选择会更有效:

  Even <- numbers[ ! sapply( numbers, ‘%%’ , 2) ]

翻译为:选择不为零且模除以零的值。忽略否定就可以发现赔率。