简体   繁体   English

有没有办法将带有数字的字符串转换为 R 中的数值列表?

[英]is there a way to convert a string with numbers to a list of numeric values in R?

Supose I have the following假设我有以下

l="1,2,3,4,5" l="1,2,3,4,5"

How do I get the sequence of numeric values如何获取数值序列

1 2 3 4 5 1 2 3 4 5

I've already seen this example https://statisticsglobe.com/convert-character-to-numeric-in-r/ But it doesn't quite match with the problem above.我已经看过这个例子https://statisticsglobe.com/convert-character-to-numeric-in-r/但它与上面的问题不太匹配。

This is one way of doing this:这是这样做的一种方法:

library(stringr)

l="1,2,3,4,5"
as.numeric(str_split(l, ',', simplify = TRUE))

1) scan will convert such a string to a numeric vector. 1) scan 会将这样的字符串转换为数字向量。 Omit the quiet argument if you would like it to report the length of the result.如果您希望它报告结果的长度,请忽略 quiet 参数。 No packages are used.不使用任何包。

x <- "1,2,3,4,5"
scan(text = x, sep = ",", quiet = TRUE)
## [1] 1 2 3 4 5

2) If what you have is actually a vector of comma separated character stings. 2)如果你所拥有的实际上是一个逗号分隔的字符串向量。 xx.二十。 and a list of numeric vectors is wanted then lapply over them.并且需要一个数字向量列表,然后覆盖它们。

xx <- c(x, x)
lapply(xx, function(x) scan(text = x, sep = ",", quiet = TRUE))
## [[1]]
## [1] 1 2 3 4 5
## 
## [[2]]
## [1] 1 2 3 4 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM