从包含数字和字符的列表中删除字符,而不包括NA强制消息。

huangapple go评论62阅读模式
英文:

Remove characters from list which contains numeric and characters without NA coercion message

问题

I've got a list which contains numbers and text items. I want to remove the text items and keep the numeric items. I don't mind using a few lines of code, So I can do the below with with x, then remove the NAs using another line. BUT I want to avoid the NAs coercion warning message.

x <- c(1, "_2", 3, 6, "1_", "a")
as.numeric(x)
[1]  1 NA  3  6 NA NA
Warning message:
NAs introduced by coercion

Any help is greatly appreciated. Thanks in advance.

英文:

I've got a list which contains numbers and text items. I want to remove the text items and keep the numeric items. I don't mind using a few lines of code, So I can do the below with with x, then remove the NAs using another line. BUT I want to avoid the NAs coercion warning message.

x &lt;- c(1,&quot;_2&quot;,3 , 6 , &quot;1_&quot; , &quot;a&quot;)
as.numeric(x)
[1]  1 NA  3  6 NA NA
Warning message:
NAs introduced by coercion 

Any help is greatly appreciated. Thanks in advance.

答案1

得分: 1

你可以使用基本的 R 中的 grep 来获取只包含数字的值,即 ^\\d+$,或者使用 \\D 来获取包含非数字的值,然后反转正则表达式以匹配只包含数字的值:

as.numeric(grep("\\D", x, value = TRUE, invert = TRUE))
[1] 1 3 6

as.numeric(grep("^\\d+$", x, value = TRUE))
[1] 1 3 6
英文:

You could use grep from base R to get values that only contain digits ie ^\\d+$ or use \\D to get those that contain non-digits and invert the regex to match only digits:

as.numeric(grep(&quot;\\D&quot;, x, value = TRUE, invert = TRUE))
[1] 1 3 6

as.numeric(grep(&quot;^\\d+$&quot;, x, value = TRUE))
[1] 1 3 6

答案2

得分: 1

We can use suppressWarnings to muffle the warnings

suppressWarnings(as.numeric(x))
[1]  1 NA  3  6 NA NA

Or with str_subset

library(tidyr)
as.numeric(str_subset(x, "^\\d+$"))
[1] 1 3 6
英文:

We can use suppressWarnings to muffle the warnings

suppressWarnings(as.numeric(x))
[1]  1 NA  3  6 NA NA

Or with str_subset

library(tidyr)
as.numeric(str_subset(x, &quot;^\\d+$&quot;))
[1] 1 3 6

</details>



huangapple
  • 本文由 发表于 2023年2月18日 04:23:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75488957.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定