[英]how to convert single character vector to numeric in R?
one column of my dataset looks like below;我的数据集的一列如下所示;
"[3, 4, 5, 6]"
and I want to split every single value of this vector-like below as numeric;我想将下面这个向量的每个值都拆分为数字;
3, 4, 5, 6
What can I do?我能做些什么?
Thank you for your answers.谢谢您的回答。
Remove the brackets and split the string using the commas.删除括号并使用逗号分隔字符串。 strsplit()
returns a list. strsplit()
返回一个列表。 You want a vector, so let us unlist()
it and convert it to numerics.你想要一个向量,所以让我们unlist()
它并将其转换为数字。
x <- "[3, 4, 5, 6]"
x <- gsub("\\[|\\]","", x)
y <- as.numeric(unlist(strsplit(x, ",", fixed=TRUE)))
y
#> [1] 3 4 5 6
Created on 2021-05-01 by the reprex package (v2.0.0)由代表 package (v2.0.0) 于 2021 年 5 月 1 日创建
For this vector对于这个向量
x = "[3, 4, 5, 6]"
find all matches of a sequence of 1 or more digits and extract the matches from the original location查找 1 个或多个数字序列的所有匹配项,并从原始位置提取匹配项
match = gregexpr("[[:digit:]]+", x)
values = regmatches(x, match)
This is a list of character values;这是一个字符值列表; coerce to integer, eg, allowing x
to be more than length 1强制到 integer,例如,允许x
大于长度 1
lapply(values, as.integer)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.