[英]how to convert a string into numeric values in R
我有一個類似“ [0 0.1 0.2 0.4]”的字符串,我想要的是去除括號並以數字形式檢索值。 我可以去除括號,但是當涉及到轉換為數字時,則出現NA錯誤:
cleanList <- function(aString){
temp <- gsub("\\[|\\]", "", aString)
as.numeric(temp)
}
有沒有一種方法可以將字符串中的每個字符轉換為數字?
編輯:這是使用縱梁的另一種方法:
cleanList <- function(aString){
as.numeric(str_extract_all(aString,"\\(?[0-9,.]+\\)?")[[1]])
}
cleanList("[0 0.1 0.2 0.4]")
[1] 0.0 0.1 0.2 0.4
您需要將temp
拆分為一個向量,然后在其上調用as.numeric
。 假設temp
中的數字用空格隔開,
temp2 <- unlist(strsplit(temp, " "))
as.numeric(temp2)
# 0.0 0.1 0.2 0.4
另外, do.call(as.numeric, strsplit(temp, " "))
也可以工作。
使用strsplit
:
as.numeric( strsplit( temp, " " )[[1]] )
有關詳細信息,請參見?strsplit
上的文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.