【问题标题】:R - find highest number of repeated digits in a single numberR - 查找单个数字中重复数字的最大数量
【发布时间】:2020-04-17 21:30:46
【问题描述】:

是否有一个函数可以返回给定数字的最大顺序重复数字?

所需的输出是以下数字的“Num_repeats”部分:

Number                     Num_repeats
18.25328700000000026193    9
18.09606604359100042883    3
17.95982782048729065186    0

【问题讨论】:

  • 'Number'中有没有字符列
  • 否 -- number 是我的数据集中的数字列
  • 好的,那么很难复制您可以使用as.character 转换为字符并使用strsplit 的数字精度
  • 是的,我现在很遗憾地意识到这一点——否则你的解决方案是完美的!
  • 如果我认为它是数字的,那么我的系统上的值会发生变化。最好使用dput来展示示例

标签: r


【解决方案1】:

如果是字符列,我们可以用strsplit分割,用rle提取相邻重复元素的length,用max返回`max``值

df1$Num_repeats <- sapply(strsplit(df1$Number, "[.]|"),
           function(x) with(rle(x), max(lengths)))
df1$Num_repeats[df1$Num_repeats==1] <- 0
df1
#                    Number Num_repeats
#1 18.25328700000000026193           9
#2 18.09606604359100042883           3 
#3 17.95982782048729065186           0

数据

df1 <-  structure(list(Number = c("18.25328700000000026193", 
     "18.09606604359100042883", 
"17.95982782048729065186")), class = "data.frame", row.names = c(NA, 
-3L))

【讨论】:

    【解决方案2】:

    另一种基础 R 解决方案

    df <- within(df,
                 Num_repeats <- sapply(gsub("\\D","",Number,perl = TRUE),
                                       function(x) (u<-max(rle(utf8ToInt(x))$lengths))*(u>1)))
    

    或者更简单的

    df <- within(df,
                 Num_repeats <- sapply(Number,
                                       function(x) (u<-max(rle(utf8ToInt(x))$lengths))*(u>1)))
    

    这样

    > df
                       Number Num_repeats
    1 18.25328700000000026193           9
    2 18.09606604359100042883           3
    3 17.95982782048729065186           0
    

    数据

    df <- structure(list(Number = c("18.25328700000000026193", "18.09606604359100042883", 
    "17.95982782048729065186")), row.names = c(NA, -3L), class = "data.frame")
    

    【讨论】:

    • 我认为这可以简化一点,因为不会有两个重复的点:sapply(x, function(i) {tmp &lt;- max(rle(utf8ToInt(i))$lengths); tmp * (tmp &gt; 1) })
    猜你喜欢
    • 2015-05-10
    • 2022-11-19
    • 2016-01-21
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多