Skip to content

Instantly share code, notes, and snippets.

@kurogelee
Created February 10, 2015 23:21
Show Gist options
  • Save kurogelee/329645af04158c9a23b4 to your computer and use it in GitHub Desktop.
Save kurogelee/329645af04158c9a23b4 to your computer and use it in GitHub Desktop.
Rでデータフレームを行ごと・列ごとに処理した結果を再度データフレームに戻す ref: http://qiita.com/kurogelee/items/9e27fd8241e92fd9dd82
df <- data.frame(x=1:3,y=3:5,z=5:7)
# 行ごと
data.frame(t(apply(df, 1, function(d){ c(d, Z=sum(d)) })))
data.frame(do.call(rbind, lapply(split(df, 1:nrow(df)), function(d){ c(d, Z=sum(d)) })))
# 列ごと
data.frame(apply(df, 2, function(d){ c(d, sum(d)) }))
data.frame(do.call(cbind, lapply(df, function(d){ c(d, sum(d)) })))
> df <- data.frame(x=1:3,y=3:5,z=5:7)
>
> # 行ごと
> data.frame(t(apply(df, 1, function(d){ c(d, Z=sum(d)) })))
x y z Z
1 1 3 5 9
2 2 4 6 12
3 3 5 7 15
> data.frame(do.call(rbind, lapply(split(df, 1:nrow(df)), function(d){ c(d, Z=sum(d)) })))
x y z Z
1 1 3 5 9
2 2 4 6 12
3 3 5 7 15
>
> # 列ごと
> data.frame(apply(df, 2, function(d){ c(d, sum(d)) }))
x y z
1 1 3 5
2 2 4 6
3 3 5 7
4 6 12 18
> data.frame(do.call(cbind, lapply(df, function(d){ c(d, sum(d)) })))
x y z
1 1 3 5
2 2 4 6
3 3 5 7
4 6 12 18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment