合并列时如何删除缺失值(NA)?

Jol*_*n J 3 r na dplyr

我正在尝试使用 Unite 函数将 5 列合并为一个新列。但是,所有行都包含许多 NA 值,创建的变量看起来像

Mother|NA|NA|NA|NA
NA|NA|Father|Mother|NA
Mother|Father|NA|Stepmother|NA
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下代码将它们联合起来:

df2 <- df %>%
unite(Parent_full, Parent:Parent5, sep = "|", remove = TRUE, na.rm = TRUE) 
Run Code Online (Sandbox Code Playgroud)

但这给了我以下错误:错误:TRUE必须评估列位置或名称,而不是逻辑向量

我也看了论坛,发现可能unite的na.rm功能没有激活?

这是一些重新创建我的数据集的数据

Name <- c('Paul', 'Edward', 'Mary')
Postalcode <- c('4732', '9045', '3476')
Parent <- c('Mother', 'NA', 'Mother')
Parent2 <- c('NA', 'NA', 'Father')
Parent3 <- c('NA', 'Father', 'NA')
Parent4 <- c('NA', 'Mother', 'Stepmother')
Parent5 <- c('NA', 'NA', 'NA')

df <- data.frame(Name, Postalcode, Parent, Parent2, Parent3, Parent4, Parent5)
Run Code Online (Sandbox Code Playgroud)

很想知道如何在没有 NA 的情况下统一我的专栏。

更新:

我现在更新了 tidyr 包,并在 read_csv 命令中添加了“na = c("", "NA")”。

现在

df2 <- df %>%
unite(Parent_full, Parent:Parent5, sep = "|", remove = TRUE, na.rm = TRUE) 
Run Code Online (Sandbox Code Playgroud)

命令有效,但由于某些原因,值末尾的 NA 保持不变。现在我的列看起来像这样:

Mother|NA
Father|Mother|NA
Mother|Father|Stepmother|NA
Does anyone know what went wrong now?
Run Code Online (Sandbox Code Playgroud)

Ron*_*hah 5

你有几个问题,

1) NAs 不是实数NA(Check is.na(df$Parent2))

2)你的列是因素

在构建数据框时使用 stringsAsFactors = FALSE

df <- data.frame(Name, Postalcode, Parent, Parent2, Parent3, Parent4, 
                 Parent5, stringsAsFactors = FALSE)
Run Code Online (Sandbox Code Playgroud)

然后更换NA并使用unite

library(dplyr)
df %>%
  na_if('NA') %>%
  tidyr::unite(Parent_full, Parent:Parent5, sep = "|", na.rm = TRUE)

#    Name Postalcode              Parent_full
#1   Paul       4732                   Mother
#2 Edward       9045            Father|Mother
#3   Mary       3476 Mother|Father|Stepmother
Run Code Online (Sandbox Code Playgroud)

如果数据已经加载,我们可以使用 mutate_if

df %>%  
 mutate_if(is.factor, as.character) %>%
 na_if('NA') %>%
 tidyr::unite(Parent_full, Parent:Parent5, sep = "|", na.rm = TRUE)
Run Code Online (Sandbox Code Playgroud)