抑制 paste() 中的 NA [英] suppress NAs in paste()

查看:26
本文介绍了抑制 paste() 中的 NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ben Bolkerpaste2-解决方案产生 "" 当粘贴的字符串在相同位置包含 NA 时.像这样,

Ben Bolker's paste2-solution produces a "" when the strings that are pasted contains NA's in the same position. Like this,

> paste2(c("a","b", "c", NA), c("A","B", NA, NA))
[1] "a, A" "b, B" "c"    ""

第四个元素是一个""而不是一个NA 像这样,

The fourth element is an "" instead of an NA Like this,

[1] "a, A" "b, B" "c"  NA     

我为任何能够解决此问题的人提供这笔小额赏金.

I'm offering up this small bounty for anyone who can fix this.

我已阅读帮助页面 ?paste,但我不明白如何让 R 忽略 NA.我执行以下操作,

I've read the help page ?paste, but I don't understand how to have R ignore NAs. I do the following,

foo <- LETTERS[1:4]
foo[4] <- NA
foo
[1] "A" "B" "C" NA
paste(1:4, foo, sep = ", ")

得到

[1] "1, A"  "2, B"  "3, C"  "4, NA"

我想得到什么,

[1] "1, A" "2, B" "3, C" "4"

我可以这样做,

sub(', NA$', '', paste(1:4, foo, sep = ", "))
[1] "1, A" "2, B" "3, C" "4"

但这似乎是绕道而行.

推荐答案

为了达到true-NA"的目的:似乎最直接的方法就是将paste2返回的值修改为当值为 ""

For the purpose of a "true-NA": Seems the most direct route is just to modify the value returned by paste2 to be NA when the value is ""

 paste3 <- function(...,sep=", ") {
     L <- list(...)
     L <- lapply(L,function(x) {x[is.na(x)] <- ""; x})
     ret <-gsub(paste0("(^",sep,"|",sep,"$)"),"",
                 gsub(paste0(sep,sep),sep,
                      do.call(paste,c(L,list(sep=sep)))))
     is.na(ret) <- ret==""
     ret
     }
 val<- paste3(c("a","b", "c", NA), c("A","B", NA, NA))
 val
#[1] "a, A" "b, B" "c"    NA    

这篇关于抑制 paste() 中的 NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆