【问题标题】:From [0.2, 0.2, 0.2] to "R 0.2 3"从 [0.2, 0.2, 0.2] 到“R 0.2 3”
【发布时间】:2017-07-10 05:21:56
【问题描述】:

我在 R 中有一个长向量,其中连续的值经常重复。例如

x = c(rep(0.2, 1500), rep(0.1, 10007), 0.7, 0.9, rep(0.1, 9784))

我正在尝试编写一个以该向量作为输入并返回以下两个字符串之一的函数

s = "R 0.2 1500 R 0.1 10007 R 0.7 1 R 0.9 1 R 0.1 9784"

或优先

s = "R 0.2 1500 R 0.1 10007 0.7 0.9 R 0.1 9784"

,其中R 0.7 1 R 0.9 1 变成了0.7 0.9

根据您的直觉,R 代表repeatrep。因此,该字符串与我构造向量 x 的方式非常相似。

我尝试循环遍历每个值,但这对于我的需要来说太慢了。你能帮我找到一个快速的解决方案吗?

【问题讨论】:

  • 你看过rle吗?
  • rle 确实是要走的路。您可以从 cmets 中建议的 3 个答案中的任何一个中做出答案。

标签: r string parsing vector


【解决方案1】:
#Data
x = c(rep(0.2, 1500), rep(0.1, 10007), 0.7, 0.9, rep(0.1, 9784))

#Run rle and paste values and lengths together
y = paste("R", rle(x)$values, rle(x)$lengths)

#There may be an easier way to do this using regex
#But here is one solution using strsplit
#Remove 1 and R
y = sapply(strsplit(y," "), function(a)
    if (gsub(" ","",a[3]) == "1"){
        a = a[2]
    } else {
    a = a
    }
)

#Collapse everything together
paste(unlist(y), collapse = " ")
#[1] "R 0.2 1500 R 0.1 10007 0.7 0.9 R 0.1 9784"

【讨论】:

    猜你喜欢
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    相关资源
    最近更新 更多