2017-06-22 250 views
2

我有以下r中數據幀查找最大值和最小值爲偶數和奇數

ID  numbers 
1  12 
2  4 
3  13 
4  8 
5  9 
6  4 

我想找到最大和最小的奇數和偶數列數和標記,

ID  numbers  Tag 
1  12   Largest even 
2  4   Smallest even 
3  13   Largest odd 
4  8   
5  9   Smallest odd 
6  4   Smallest even 

我試着做下列

df$tag <- ifelse(which.max(df$numbers %% 2 == 0),"Largest even", 
       ifelse(which.min(df$numbers %% 2 == 0),"Smallest even", 
         ifelse(which.max(df$numbers %% 2 != 0),"Largest odd", 
          ifelse(which.min(df$numbers %% 2 != 0),"Smallest odd", 

它不工作,我想要的方式。

+0

會發生什麼事時,只有1偶數? – zx8754

+0

在我的情況下,它不會發生。我至少會有兩個偶數或奇數。 – Neil

回答

2

使用dplyr,製作一組賠率/平均值,然後獲得每組最小最大值。

library(dplyr) 

df1 %>% 
    mutate(grp = if_else(numbers %% 2 == 0, "even", "odd")) %>% 
    group_by(grp) %>% 
    mutate(ID, numbers, 
     Tag = paste0(if_else(numbers == min(numbers), paste("Smallest", grp), ""), 
         if_else(numbers == max(numbers), paste("Largest", grp), ""))) %>% 
    ungroup() %>% 
    select(-grp) 

# # A tibble: 6 x 3 
#  ID numbers   Tag 
# <int> <int>   <chr> 
# 1  1  12 Largest even 
# 2  2  4 Smallest even 
# 3  3  13 Largest odd 
# 4  4  8    
# 5  5  9 Smallest odd 
# 6  6  4 Smallest even 

編輯:

df1 %>% 
    mutate(grp = if_else(numbers %% 2 == 0, "even", "odd")) %>% 
    group_by(grp) %>% 
    mutate(ID, numbers, 
     Tag = paste0(if_else(numbers == min(numbers), "Smallest ", ""), 
         if_else(numbers == max(numbers), "Largest ", ""), 
         grp)) %>% 
    ungroup() %>% 
    select(-grp) 

# # A tibble: 6 x 3 
#  ID numbers   Tag 
# <int> <int>   <chr> 
# 1  1  12 Largest even 
# 2  2  4 Smallest even 
# 3  3  13 Largest odd 
# 4  4  8   even 
# 5  5  9 Smallest odd 
# 6  6  4 Smallest even 
+0

在空白處打印偶數還是奇數?就像第4行一樣,它應該打印'even' – Neil

+0

@ zx8754我用'grp'代替它,但它給了我'oddLargest odd,evenLargest甚至 '類似這樣的 – Neil

+0

@Neil更新以顯示奇數/偶數,當它們不是最大或最小。 – zx8754

1

下面是一個選項,使用data.table

library(data.table) 
setDT(df1)[, Tag := paste(c("", "Smallest", "Largest")[1 + (numbers == min(numbers)) + 
    2*(numbers == max(numbers))], grp), .(grp = c('even', 'odd')[(numbers%%2)+1])] 

df1 
# ID numbers   Tag 
#1: 1  12 Largest even 
#2: 2  4 Smallest even 
#3: 3  13 Largest odd 
#4: 4  8   even 
#5: 5  9 Smallest odd 
#6: 6  4 Smallest even 
+1

謝謝@akrun。讚賞 – Neil

相關問題