将粘贴的数字转换为r中的数字向量
我想将以下字符串转换为单独的值,包括减号将粘贴的数字转换为r中的数字向量,r,substring,R,Substring,我想将以下字符串转换为单独的值,包括减号 t <- "111111111-1-1-1-1-1-1-1-11111-1-1-1-1-1111111-1-1-1-1-1-1-1-111111-1-1-1-111111-1-1-1-1-1-1-1-111111-1-1-1-1111111-1-1-1-1-1-1-1-1111-1-1-1-111111111" 非常感谢您的建议。您可以使用strsplit: as.integer(strsplit(t, "(?<=\\d)", perl =
t <- "111111111-1-1-1-1-1-1-1-11111-1-1-1-1-1111111-1-1-1-1-1-1-1-111111-1-1-1-111111-1-1-1-1-1-1-1-111111-1-1-1-1111111-1-1-1-1-1-1-1-1111-1-1-1-111111111"
非常感谢您的建议。您可以使用
strsplit
:
as.integer(strsplit(t, "(?<=\\d)", perl = TRUE)[[1]])
另一个选项是使用
gregexpr
和regmatches
:
as.integer(regmatches(t,gregexpr("\\d|-\\d",t))[[1]])
使用
stringr
的str\u extract\u all
功能
as.integer(str_extract_all(t, '-?\\d')[[1]])
结果
[1] 1 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 -1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1
[42] 1 1 1 1 -1 -1 -1 -1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 1 1 -1 -1 -1 -1 -1
[83] -1 -1 -1 1 1 1 -1 -1 -1 -1 1 1 1 1 1 1 1 1
检查
与
stringi
类似,如库(stringi);as.integer(stri_extract_all(t,regex='-?\\d')[[1]])
Wilson、mrip和David:非常感谢您的快速回答。我问对人了!
as.integer(str_extract_all(t, '-?\\d')[[1]])
[1] 1 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 -1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1
[42] 1 1 1 1 -1 -1 -1 -1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 1 1 -1 -1 -1 -1 -1
[83] -1 -1 -1 1 1 1 -1 -1 -1 -1 1 1 1 1 1 1 1 1
> nchar(t)
[1] 149
> nchar(str_replace_all(t, '\\d', ''))
[1] 49
> length(as.integer(str_extract_all(t, '-?\\d')[[1]]))
[1] 100