## 如何分割数据框架，应用某些功能，并将其重新组合在一起？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (35)

``````df = data.frame(y=1:10, g=rep(c("a", "b"), each=5))
``````

``````do.call(
rbind,
lapply(unique(df\$g),
function(level) {
y.current = df\$y[df\$g==level]

## perform some operation
y.new = (y.current-min(y.current))/
(max(y.current)-min(y.current))

return(data.frame(y=y.new,
g=level))
}
)
)
``````

``````library(dplyr)
df = data.frame(y=1:10, g=rep(c("a", "b"), each=5))
trans_df = df %>%
group_by(g) %>%
do(y=.\$y[-which.max(.\$y)])
``````

``````data.frame(g=rep(trans_df\$g, times=sapply(trans_df\$y, length)),
y=do.call(c, trans_df\$y))
``````

### 2 个回答

``````df\$y <- ave(df\$y,df\$g, FUN = function(y) (y - min(y))/(max(y) - min(y)))
#       y g
# 1  0.00 a
# 2  0.25 a
# 3  0.50 a
# 4  0.75 a
# 5  1.00 a
# 6  0.00 b
# 7  0.25 b
# 8  0.50 b
# 9  0.75 b
# 10 1.00 b
``````

``````split(df\$y,df\$g) <- tapply(df\$y, df\$g, function(y) (y - min(y))/(max(y) - min(y)))
``````

``````by_ <- by(df, df\$g, function(x) transform(x, y = (y - min(y))/(max(y) - min(y))))
do.call(rbind, by_)
#         y g
# a.1  0.00 a
# a.2  0.25 a
# a.3  0.50 a
# a.4  0.75 a
# a.5  1.00 a
# b.6  0.00 b
# b.7  0.25 b
# b.8  0.50 b
# b.9  0.75 b
# b.10 1.00 b
``````

``````df <- data.frame(y=1:10, g=rep(c("a", "b"), each=5))

library(dplyr)
df %>%
group_by(g) %>%
mutate(y2 = (y - min(y)) / (max(y) - min(y)))
#> # A tibble: 10 x 3
#> # Groups:   g [2]
#>        y g        y2
#>    <int> <fct> <dbl>
#>  1     1 a      0
#>  2     2 a      0.25
#>  3     3 a      0.5
#>  4     4 a      0.75
#>  5     5 a      1
#>  6     6 b      0
#>  7     7 b      0.25
#>  8     8 b      0.5
#>  9     9 b      0.75
#> 10    10 b      1

df %>%
group_by(g) %>%
top_n(-4, y)
#> # A tibble: 8 x 2
#> # Groups:   g [2]
#>       y g
#>   <int> <fct>
#> 1     1 a
#> 2     2 a
#> 3     3 a
#> 4     4 a
#> 5     6 b
#> 6     7 b
#> 7     8 b
#> 8     9 b
``````