如何隔离向量中存在的奇偶数。 我简化了 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
答案 0 :(得分:0)
通过逻辑选择会更有效:
Even <- numbers[ ! sapply( numbers, ‘%%’ , 2) ]
翻译为:选择不为零且模除以零的值。忽略否定就可以发现赔率。