出力する前に、クリーンアップ、名前の変更、および列の配置を行いたい計算からのデータフレームがよくあります。以下のすべてのバージョンが機能します。シンプルなdata.frame
ものが最も近いです。
最後に追加の冗長な [,....] なしで、のデータフレーム内計算と の列順序の保存を組み合わせる方法はありwithin
ますmutate
か?data.frame()
library(plyr)
# Given this chaotically named data.frame
d = expand.grid(VISIT=as.factor(1:2),Biochem=letters[1:2],time=1:5,
subj=as.factor(1:3))
d$Value1 =round(rnorm(nrow(d)),2)
d$val2 = round(rnorm(nrow(d)),2)
# I would like to cleanup, compute and rearrange columns
# Simple and almost perfect
dDataframe = with(d, data.frame(
biochem = Biochem,
subj = subj,
visit = VISIT,
value1 = Value1*3
))
# This simple solution is almost perfect,
# but requires one more line
dDataframe$value2 = dDataframe$value1*d$val2
# For the following methods I have to reorder
# and select in a second step
# use mutate from plyr to allow computation on computed values,
# which transform cannot do.
dMutate = mutate(d,
biochem = Biochem,
subj = subj,
visit = VISIT,
value1 = Value1*3, #assume this is a time consuming function
value2 = value1*val2
# Could set fields = NULL here to remove,
# but this does not help getting column order
)[,c("biochem","subj","visit","value1","value2")]
# use within. Same problem, order not preserved
dWithin = within(d, {
biochem = Biochem
subj = subj
visit = VISIT
value1 = Value1*3
value2 = value1*val2
})[,c("biochem","subj","visit","value1","value2")]
all.equal(dDataframe,dWithin)
all.equal(dDataframe,dMutate)