Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 对整数的数字随机重新排序(但';0';不应在开头)_R - Fatal编程技术网

R 对整数的数字随机重新排序(但';0';不应在开头)

R 对整数的数字随机重新排序(但';0';不应在开头),r,R,我需要对整数x(至少4个或更多数字)的数字进行随机重新排序。下面的方法可以工作,但不能确保在重新排序的值的开头永远不会出现零 如果零成为初始值,重新排序的整数将具有更少的nchar,这正是我试图避免的 x = 357230434L set.seed(42) as.integer(paste(sample(unlist(strsplit(as.character(x),""))), collapse = "")) #[1] 437324035 我还没有试过,但我可能可以用for循环来完成。然而,

我需要对整数
x
(至少4个或更多数字)的数字进行随机重新排序。下面的方法可以工作,但不能确保在重新排序的值的开头永远不会出现零

如果零成为初始值,重新排序的整数将具有更少的nchar,这正是我试图避免的

x = 357230434L
set.seed(42)
as.integer(paste(sample(unlist(strsplit(as.character(x),""))), collapse = ""))
#[1] 437324035

我还没有试过,但我可能可以用
for
循环来完成。然而,在我尝试之前,我想看看是否有更好的方法对整数的数字进行重新排序,同时确保在重新排序的整数的开头从不放零

你考虑过分多个部分做吗?可能有一种更简单的方法,但有一种方法是随机抽取第一个非零字符,然后对其余字符进行采样。比如:

  chars<-unlist(strsplit(as.character(x),""))
  first<-sample(chars[chars!="0"],1)
  as.integer(paste0(c(first,sample(chars[-match(first,chars)])),collapse=""))

我参加聚会有点晚了,但这里有另一种方法:

  • 生成一个随机排列

  • 循环移位,使其从第一个非零元素开始(
    01234
    变为
    12340

  • 代码:

    另外,不要忘记设置
    选项(scipen=16)
    或其他较大的值,否则您将在科学记数法方面遇到麻烦:

    > as.character(100000000)
    [1] "1e+08"
    

    x=0
    时,预期的行为是什么?@aryamcarthy,
    x
    的位数始终超过4位。
    # random permutation
    x2 = sample(unlist(strsplit(as.character(x), ""))) 
    # get the position of the first non-zero character
    p = which(x2 > '0')[1] 
    # make a circular rotation to put the non-zero in front
    x2[(seq_along(x2) + p-2) %% length(x2) + 1] 
    
    > as.character(100000000)
    [1] "1e+08"