英文:
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 <- 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.
答案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("\\D", x, value = TRUE, invert = TRUE))
[1] 1 3 6
as.numeric(grep("^\\d+$", 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, "^\\d+$"))
[1] 1 3 6
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论