58 列のデータフレームがあり、最初の 56 列のすべての値に変換 $log(x_{i,j}+1)$ を適用する必要があります。これを最も効率的に行うには、どの方法を使用できますか? forループを使用してデータフレーム全体を実行するだけでなく、これを可能にする何かがあると思います。
38957 次
2 に答える
37
alexwhanの答えはログに適しています(おそらく正しい答えとして選択する必要があります)。ただし、ログはベクトル化されているため、非常にきれいに機能します。私は、ベクトル化されていない関数の特別な苦痛をあまりにも頻繁に経験してきました。私が R を使い始めたとき、apply ファミリーをよく理解していなかったので、よく醜いループに頼っていました。したがって、ベクトル化された関数を持っていないこの質問に出くわす可能性のある人のために、次の概念実証を提供します。
#Creating sample data
df <- as.data.frame(matrix(runif(56 * 56), 56, 56))
#Writing an ugly non-vectorized function
logplusone <- function(x) {log(x[1] + 1)}
#example code that achieves the desired result, despite the lack of a vectorized function
df[, 1:56] <- as.data.frame(lapply(df[, 1:56], FUN = function(x) {sapply(x, FUN = logplusone)}))
#Proof that the results are the same using both methods...
#Note: I used all.equal rather than all so that the values are tested using machine tolerance for mathematical equivalence. This is probably a non-issue for the current example, but might be relevant with some other testing functions.
#should evaluate to true
all.equal(log(df[, 1:56] + 1),as.data.frame(lapply(df[, 1:56], FUN = function(x) {sapply(x, FUN = logplusone)})))
于 2013-03-05T04:49:21.017 に答える
23
必要な列を参照して、操作を実行できるはずです。つまり、次のようになります。
df[,1:56] <- log(df[,1:56]+1)
于 2013-03-05T04:33:07.490 に答える