2016-03-18 43 views
0

我是的新手,並且有以下問題。我有data.frame一列作爲分組變量。有些行不是屬於一個組,分組列是NAdplyr mutate():如果組是NA,則忽略值

我需要使用dplyr函數mutate將一些列添加到data.frame中。我寧願dplyr忽略分組列等於NA的所有行。我將舉一個例子:

library(dplyr) 

set.seed(2) 

# Setting up some dummy data 
df <- data.frame(
    Group = factor(c(rep("A",3),rep(NA,3),rep("B",5),rep(NA,2))), 
    Value = abs(as.integer(rnorm(13)*10)) 
) 

# Using mutate to calculate differences between values within the rows of a group 
df <- df %>% 
    group_by(Group) %>% 
    mutate(Diff = Value-lead(Value)) 

df 
# Source: local data frame [13 x 3] 
# Groups: Group [3] 
# 
#  Group Value Diff 
# (fctr) (int) (int) 
# 1  A  8  7 
# 2  A  1 -14 
# 3  A 15 NA 
# 4  NA 11 11 
# 5  NA  0 -1 
# 6  NA  1 -8 
# 7  B  7  5 
# 8  B  2 -17 
# 9  B 19 18 
# 10  B  1 -3 
# 11  B  4 NA 
# 12  NA  9  6 
# 13  NA  3 NA 

計算沒有組的行之間的差異是沒有意義的,並且正在破壞數據。我需要刪除這些行,有一個像這樣這樣做:

df$Diff[is.na(df$Group)] <- NA 

有沒有一種方法,包括上面的命令到使用%>%的dplyr鏈?在行的某處:

df <- df %>% 
    group_by(Group) %>% 
    mutate(Diff = Value-lead(Value)) %>% 
    filter(!is.na(Group)) 

但是,沒有組的行不會一起被刪除嗎?或者甚至更好,有沒有一種方法可以使dplyr在沒有組的情況下忽略行?

有希望的結果將是:

# Source: local data frame [13 x 3] 
# Groups: Group [3] 
# 
#  Group Value Diff 
# (fctr) (int) (int) 
# 1  A  8  7 
# 2  A  1 -14 
# 3  A 15 NA 
# 4  NA 11 NA 
# 5  NA  0 NA 
# 6  NA  1 NA 
# 7  B  7  5 
# 8  B  2 -17 
# 9  B 19 18 
# 10  B  1 -3 
# 11  B  4 NA 
# 12  NA  9 NA 
# 13  NA  3 NA 

回答

4

只需使用iflelse條件,你要創建的變量:

library(dplyr) 
set.seed(2) 

df = data.frame(
    Group = factor(c(rep("A",3), rep(NA,3), rep("B",5), rep(NA,2))), 
    Value = abs(as.integer(rnorm(13)*10)) 
) %>% 
    group_by(Group) %>% 
    mutate(Diff = ifelse(is.na(Group), as.integer(NA), Value-lead(Value))) 
+0

常見的用法是'NA_integer_'一個內建的常數,僅供參考。 – Frank

+0

@Frank解決完全相同的事情:'相同(as.integer(NA),NA_integer_)',我不太瞭解「通常」。 – tchakravarty

+0

夠公平的。按照「平常」,我的意思是我見過的唯一方法。 – Frank