r-如何生成嵌套字符串的矢量



在数据帧a中,变量b是嵌套的字符列表。

> class(a$b)
[1] "character"
> a$b[2]
[1] "[1034974, 1008535, 1008552, ..., 1008682]"
dput(a$b[1:2)
c("[1034974, 1008535, 1008552, ..., 1008578]", 
"[1034974, 1008535, 1008552, 1000001, ..., 1301205, 1008682]")

我想产生一个所有这些值的向量。thx提前

您需要拆分字符串值并将其转换为整数。请参阅以下代码作为示例:

require(stringr)
string1 <- "[1034974, 1008535, 1008552, 1008682]"
string2 = str_remove(string1, "\[") #remove the open bracket [
string3 = str_remove(string2, "\]") #remove the close bracket ]
string4 = str_replace_all(string3, " ", "") #remove the spaces
string5 = strsplit(string4, ",")[[1]] #split the string values
int = as.integer(string5) #convert to integer
print(int)

最新更新