差分
この文書の現在のバージョンと選択したバージョンの差分を表示します。
両方とも前のリビジョン 前のリビジョン 次のリビジョン | 前のリビジョン | ||
memo:r:datamanipulationwithr [2013/07/22 06:06] hasegawa |
memo:r:datamanipulationwithr [2016/07/17 04:22] (現在) |
||
---|---|---|---|
ライン 67: | ライン 67: | ||
res[i] <- i^2 | res[i] <- i^2 | ||
} | } | ||
+ | res | ||
+ | |||
+ | 2013/07/31追記 | ||
+ | NULLで初期化した方が楽で良いようだ. | ||
+ | res <- NULL | ||
+ | for (i in 1:10){ | ||
+ | res[i] <- i^2 | ||
+ | } | ||
+ | res | ||
====== データフレーム dataframe ====== | ====== データフレーム dataframe ====== | ||
ライン 115: | ライン 124: | ||
48 4.6 3.2 1.4 0.2 setosa | 48 4.6 3.2 1.4 0.2 setosa | ||
+ | # iris$Sepal.Lengthが4.3, 4.4, 4.5, 4.6のいずれかに一致しない行を抽出 | ||
+ | iris[!(iris$Sepal.Length %in% c(4.3, 4.4, 4.5, 4.6)), ] | ||
- | ===== データフレームの並べ替え ===== | + | ===== データフレーム行の並べ替え ===== |
iris[order(iris$Sepal.Length), ] # "Sepal.Length"の値で昇順に並べ替え | iris[order(iris$Sepal.Length), ] # "Sepal.Length"の値で昇順に並べ替え | ||
iris[order(iris$Sepal.Length, decreasing=TRUE), ] # "Sepal.Length"の値で降順に並べ替え | iris[order(iris$Sepal.Length, decreasing=TRUE), ] # "Sepal.Length"の値で降順に並べ替え | ||
iris[sample(nrow(iris)), ] # ランダムに並べ替え | iris[sample(nrow(iris)), ] # ランダムに並べ替え | ||
+ | |||
+ | ===== データフレームの行と列の入れ替え ===== | ||
+ | matrixの場合はt()関数が用意されているが,データフレームにはない(t()関数を適用出来るが,列名が変になることがある).簡単な処理なので関数にするまでもないが,あえて関数にすればこんな感じ. | ||
+ | # データフレーム df の行と列を入れ替える関数 | ||
+ | TransposeDf <- function(df){ | ||
+ | # データフレームを転置 | ||
+ | tdf <- data.frame(t(df)) | ||
+ | # 行名と列名を付けなおす | ||
+ | rownames(tdf) <- colnames(df) | ||
+ | colnames(tdf) <- rownames(df) | ||
+ | return(tdf) | ||
+ | } | ||
+ | | ||
+ | # 実行例 | ||
+ | TransposeDf(df = iris) | ||
+ | |||
====== 行列 matirix ====== | ====== 行列 matirix ====== |