【问题标题】:How can I add a new column based on NA values of another column?如何根据另一列的 NA 值添加新列?
【发布时间】:2019-09-01 07:09:52
【问题描述】:

我需要根据具有 NA 值的列的某些条件和其他列的值在 R 中创建一个新列。

我尝试了以下代码,例如:

expr1 <- data.frame(from =c("S01", "S02"),to1= c("S02", "S03"),tel=c(123,456))

expr2 <- data.frame(from =c("S01", "S04"),to2= c("S02", "S05"),post=c('ABC','XYZ'))



exp <- full_join(expr1, expr2,by="from") 

exp

现在我想创建一个名为 to 的新列,它可以为我提供一个新列的值:

类似于名为“to”的列,其值为 S02 S03 S05。所以'to'类似于

ifelse(is.na(exp$to1)== TRUE,exp$to=exp$to2 , exp$to=exp$to1)

【问题讨论】:

  • ?dplyr::coalesceis.na(exp$to1) 也将返回 T/F 不需要做 is.na(exp$to1)==TRUE

标签: r join dplyr


【解决方案1】:

如果您只能从两列中选择,这里有一些选项。

在基础 R 中,您可以使用 ifelse

exp$to <- with(exp, ifelse(is.na(to1), to2, to1))

#  from  to1 tel  to2 post  to
#1  S01  S02 123  S02  ABC S02
#2  S02  S03 456 <NA> <NA> S03
#3  S04 <NA>  NA  S05  XYZ S05

使用dplyr,可以使用case_when

library(dplyr)
exp %>%
  mutate(to = case_when(is.na(to1)~to2, 
                        TRUE ~to1))

coalesce

exp %>% mutate(to = coalesce(to1, to2))

但是,如果您有多个 "to" 列可供选择,并且不想为每个列单独编写 if else 条件,我们可以使用 grep 选择 to_cols 并使用 max.col 获得第一个非-NA 每行的值。

to_cols <- grep("^to", names(exp))
exp$to <- exp[to_cols][cbind(seq_len(nrow(exp)), 
          max.col(!is.na(exp[to_cols]), ties.method = "first"))]

数据

如果您在 data.frame 创建中添加 stringsAsFactors = FALSE,生活会简单得多

expr1 <- data.frame(from =c("S01", "S02"),to1= c("S02", "S03"),
                    tel=c(123,456), stringsAsFactors = FALSE)
expr2 <- data.frame(from =c("S01", "S04"),to2= c("S02", "S05"),
                    post=c('ABC','XYZ'), stringsAsFactors = FALSE)
exp <- full_join(expr1, expr2,by="from") 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多