如何将数字序列分成相等大小的块并保存在R中的列表中

我是R的新手。 我正在尝试将一系列数字分成相等大小的块, 例如, X

数字例如9777879779709779729780769786769788319811329818839836719842649852659858069860649863469869099877499829829889599891659907469910019925359927479934829935069942939948739961029929977409982909984589987819992959994649991999。

YOZA007 回答:如何将数字序列分成相等大小的块并保存在R中的列表中

尝试一下。将花括号内的数字更改为所需的长度。请注意,最后一块可能短于所需长度。

 if($count == 0){?>  //here

  <form action="{{url('/addToWishList')}}" method="post">
  {{csrf_field()}}
  <input type="hidden" value="{{$productdata->id}}"  name="pro_id"/>
  <button type="submit" value="Add to WishList" class="wishlist-btn btn-success"><i class="fa fa-heart"></i><span>Add to WishList</span></button>
  </form>

<?php } else {?>

要确保字符串长度可以被6整除,可以事先使用此检查。

strsplit('012345678910232122',perl = TRUE,"(?<=\\d{6})")
# [[1]]
# [1] "012345" "678910" "2321" 
,

假设您的输入是字符串,即:

s <- "977787977970977972978076978676978831981132981883983671984264985265985806986064986346986909987749988622988959989165990746991001992535992747993482993506994293994873996102997740998210998458998781999295999464999529"
  • 解决方案1 ​​ :您可以使用substr代码将字符串分成大小为6的块
lapply(seq(nchar(s)/6),function(k) substr(s,6*(k-1)+1,6*k))
  • 解决方案2 :您可以制作矩阵来表示块
Map(intToUtf8,data.frame(matrix(utf8ToInt(s),nrow = 6)))

及其有效版本是

apply(matrix(utf8ToInt(s),nrow = 6),2,intToUtf8)
,

Base R解决方案(返回向量而不是列表):

n = 6

split_positions <- which(1:nchar(X) %% n == 0)

# As vector: 

sapply(split_positions,function(y){paste(unlist(strsplit(X,""))[y:(y+(n-1))],collapse = "")})

# As list: 

lapply(split_positions,collapse = "")})

数据:

X <- "977787977970977972978076978676978831981132981883983671984264985265985806986064986346986909987749988622988959989165990746991001992535992747993482993506994293994873996102997740998210998458998781999295999464999529"
,

这是使用substring

的一种方法
get_split_vec <- function(X) {
    n <- round(nchar(X)/2)
    list(substring(X,1,n),substring(X,n+1))
}

get_split_vec(123456798123)

#[[1]]
#[1] "123456"

#[[2]]
#[1] "798123"
本文链接:https://www.f2er.com/3086640.html

大家都在问