0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【R言語】指定した複数の変数削除

Last updated at Posted at 2018-03-29

1つのvariable削除

remove(variable)
# removeはrmと短縮記述も可能

全部のvariable削除

remove(list = ls())
# ls()で変数名一覧を呼び出している

複数の指定したvariable削除

remove(list = c("variableName1","variableName2"))

ここで実はちょっとはまりました。

私のやっていた処理では、処理対象の名前を持つloadNameList がありました。
それに演算した結果を"a" + loadNamelist[x]で保持していました。
用済みになったのでこのlistで作った変数を削除しようと以下コマンドを実行しました。

loadNameList <- c("123","456");
removeNameList <- list()
for(i in loadNameList)
{
  removeNameList <- c(removeNameList, sprintf("%s%s","a",i))
}
remove(list = removeNameList) 

するとエラー

Error in remove(list = removeNameList) : invalid first argument

なんでじゃ!?
と言うことで確認。

> ls()
  [1] "a123"                     "a456" 

> removeNameList
[[1]]
[1] "a123"

[[2]]
[1] "a456"

つまりベクトルとlistの概念を理解していなかったと言うことですね。

# remove(list = 文字列ベクトル)でなければならない
remove(list = "a123") #これはOK
remove(list = a123) #これはNG そもそもremove(a123)で良いのですが

自信ないですがRでは

  • データの最小構造はベクトル
  • 「1」や「"a"」は長さ1のベクトル
  • c(1,2)は長さ2のベクトル

と言うことのようです。

ベクトルとして扱うために以下の様にすると実行できました。

removeNameList <- c()#空のベクトルとして宣言
for(i in loadNameList)
{
  removeNameList <- c(removeNameList, sprintf("%s%s","a",i))
}

または

removeNameList <- list()
for(i in loadNameList)
{
  removeNameList <- c(removeNameList, sprintf("%s%s","a",i))
}
remove(list= unlist(removeNameList))#unlistでベクトルに変換できる。

うーん、中々慣れないと良く分からんですね。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?