如何使用dplyr中的coalesce()函数(有例子)

385 阅读2分钟

你可以使用R中dplyr包中的coalesce()函数来返回一个或多个向量中每个位置的第一个非遗漏值。

有两种常见的方法来使用这个函数。

方法1:替换向量中的缺失值

library(dplyr)

#replace missing values with 100
coalesce(x, 100)

方法2:返回数据框架各列的第一个非遗漏值

library(dplyr)

#return first non-missing value at each position across columns A and B
coalesce(df$A, df$B)

下面的例子展示了如何在实践中使用每种方法。

例1:使用coalesce()替换向量中的缺失值

下面的代码显示了如何使用coalesce()函数将一个向量中的所有缺失值替换为100的值:

library(dplyr)

#create vector of values
x <- c(4, NA, 12, NA, 5, 14, 19)

#replace missing values with 100
coalesce(x, 100)

[1]   4 100  12 100   5  14  19

请注意,原始向量中的每个缺失值都被替换成了100的值。

例2: 使用coalesce()返回数据框各列中第一个非缺失值

假设我们在R中拥有以下数据框:

#create data frame
df <- data.frame(A=c(10, NA, 5, 6, NA, 7, NA),
                 B=c(14, 9, NA, 3, NA, 10, 4))

#view data frame
df

   A  B
1 10 14
2 NA  9
3  5 NA
4  6  3
5 NA NA
6  7 10
7 NA  4

下面的代码显示了如何使用coalesce()函数来返回数据框中A列和B列的第一个非遗漏值:

library(dplyr)

#create new column that coalesces values from columns A and B
df$C <- coalesce(df$A, df$B)

#view updated data frame
df

   A  B  C
1 10 14 10
2 NA  9  9
3  5 NA  5
4  6  3  6
5 NA NA NA
6  7 10  7
7 NA  4  4

结果C列包含了A列和B列的第一个非缺失值。

请注意,第5行的C列的值为NA,因为A列和B列在该行都有NA值。

我们可以简单地在 coalesce()函数中增加一个值,如果每一列中恰好有NA值,就可以将其作为值:

library(dplyr)

#create new column that coalesces values from columns A and B
df$C <- coalesce(df$A, df$B, 100)

#view updated data frame
df

   A  B   C
1 10 14  10
2 NA  9   9
3  5 NA   5
4  6  3   6
5 NA NA 100
6  7 10   7
7 NA  4   4

请注意,C列第5行的NA值现在已经被一个100的值所取代。