裏 RjpWiki

Julia ときどき R, Python によるコンピュータプログラム,コンピュータ・サイエンス,統計学

insert, pop, count, index, concat, remove を定義する

2019年08月28日 | ブログラミング

R には,ベクトルに要素を挿入する append があるが,関連する他の関数がないので作ってみた。

 

1. 要素の挿入 index(x, a, pos=length(x)) ベクトル x の pos 位置に a を挿入する。先頭に加える場合は pos=0 とする。

insert = function(x, a, pos=length(x)) {
  assign(deparse(substitute(x)), append(x, a, after=pos), envir = .GlobalEnv)
}

> x = c('w', 'q', 'p', 'w')
> insert(x, 'first', 0)
> insert(x, 'last')
> x
[1] "first" "w"     "q"     "p"     "w"     "last"

2. 要素の取り出し pop(x, pos=length(x)) ベクトル x の pos 位置にある要素を取除く。取り除かれた値を返す。

pop = function(x, pos=length(x)) {
  assign(deparse(substitute(x)), x[-pos], envir = .GlobalEnv)
  return(x[pos])
}

> a = c('1', '2', 'a', 'x')
> pop(a, 1)
[1] "1"
> a
[1] "2" "a" "x"
> pop(a)
[1] "x"
> a
[1] "2" "a"

3. 要素の個数 count(x, a) ベクトル x の中に a がいくつあるかを返す。

count = function(x, a) {
  sum(x %in% a)
}

> x = c('w', 'q', 'p', 'w')
> count(x, "w")
[1] 2

4. 要素の位置 index(x, a) ベクトル x において, a がある位置を返す。なければ 0,複数ある場合は最初のものの位置を返す。

index = function(x, a) {
  ans = which(x == a)
  if (length(ans) >= 1) {
    return(ans[1])
  } else {
    return(0)
  }
}

> a = c('1', '2', 'a', 'x')
> index(a, '3')
[1] 0
> index(a, '1')
[1] 1
> index(a, 'a')
[1] 3

5. 連結 指定した複数のベクトルを連結したものを返す。

concat = function(a, b, ...) {
  others = list(...)
  ret = c(a, b)
  len = length(others)
  if (len != 0) {
    for (i in seq_along(others)) {
      ret = c(ret, others[[i]])
    }
  }
  return(ret)
}

> alp = c("a", "b", "c")
> num = c("1", "2", "3")
> sym = c("@", "*", "/")
> foo = c("x", "y", "z", "w")
> concat(alp, num)
[1] "a" "b" "c" "1" "2" "3"
> concat(alp, num, sym, foo)
 [1] "a" "b" "c" "1" "2" "3" "@" "*" "/" "x" "y"
[12] "z" "w"

6. 消去 remove(x, a) ベクトル x から,要素 a を取り除く。

remove = function(x, a) {
  ans = which(x == a)
  if (length(ans) >= 1) {
    assign(deparse(substitute(x)), x[-ans], envir = .GlobalEnv)
  }
}

> x = c('a', 'b', 'c')
> remove(x, "w")
> x
[1] "a" "b" "c"
> remove(x, "a")
> x
[1] "b" "c"






 

コメント    この記事についてブログを書く
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする
« 連続変数をカテゴリー化する | トップ | bincombinations から n-comb... »
最新の画像もっと見る

コメントを投稿

ブログラミング」カテゴリの最新記事