Re: [问题] 循环数列

楼主: celestialgod (天)   2016-04-26 21:31:03
※ 引述《PILIPALAPON (pilipalapon)》之铭言:
: [问题类型]:
: 程式资讯
: [软件熟悉度]:
: 入门
: [问题叙述]:
: a为7个1到7随机取后不放回的数
: a=sample(1:7,7,replace=T)
: 当a为1时 b=2 c=3 d=4 e=5 f=6 g=7
: 当a为2时 b=3 c=4 d=5 e=6 f=7 g=1
: 当a为3时 b=4 c=5 d=6 e=7 f=1 g=2
: 以此类推...
: [程式范例]:
: 目前只想到用循环直接写,想请版友提供更快更好的方法
: [环境叙述]:
: R3.2.4
a <- sample.int(7L, 7L) # [1] 6 7 2 5 1 3 4
out <- sweep(replicate(7L, 1L:7L), 2, a, '+')
out[out > 7] <- out[out > 7] - 7
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] 7 1 3 6 2 4 5
# [2,] 1 2 4 7 3 5 6
# [3,] 2 3 5 1 4 6 7
# [4,] 3 4 6 2 5 7 1
# [5,] 4 5 7 3 6 1 2
# [6,] 5 6 1 4 7 2 3
# [7,] 6 7 2 5 1 3 4
# 一次pipe得到答案 (这个绝对是太无聊):
library(pipeR)
library(plyr)
sample.int(7L, 7L) %>>% (sweep(replicate(7L, 1L:7L), 2, ., '+')) %>>%
mapvalues(8:14, 1:7)

Links booklink

Contact Us: admin [ a t ] ucptt.com