提问者:小点点

dplyr mutate():如果组为NA,则忽略值


我是dplyr的新手,有以下问题。我的有data. frame一列作为分组变量。有些行不属于一个组,分组列是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-chain中

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

共1个答案

匿名用户

只需为您尝试创建的变量使用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)))