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

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

问题描述

Ben Bolker paste2解决方案在粘贴的字符串包含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返回的值修改为NA值是""

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天全站免登陆