我正在尝试扩展现有数据集,目前如下所示:
df <- tibble(
site = letters[1:3],
years = rep(4, 3),
tr = c(3, 6, 4)
)
tr 是每个站点/年份组合的重复总数。我只想添加重复项,然后添加每个重复项的响应变量。使用以下函数对于单个站点/年份组合来说很容易:
f <- function(site=NULL, years=NULL, t=NULL){
df <- tibble(
site = rep(site, each = t, times= years),
tr = rep(1:t, times = years),
year = rep(1:years, each = t)
)
df
}
# For one site:
f(site='a', years=4, t=3)
# Producing this:
# # A tibble: 12 x 3
# site tr year
# <chr> <int> <int>
# 1 a 1 1
# 2 a 2 1
# 3 a 3 1
# 4 a 1 2
# 5 a 2 2
# 6 a 3 2
# 7 a 1 3
# 8 a 2 3
# 9 a 3 3
# 10 a 1 4
# 11 a 2 4
# 12 a 3 4
如何将该函数应用于输入数据帧的每一行以生成最终数据帧?基础 r 中的 apply 函数之一或 purrr 包中的 pmap_df() 似乎是理想的,但由于不熟悉这些函数的工作原理,我所有的努力都只产生了错误。
最佳答案
如果我们想应用相同的功能,请使用pmap
library(purrr)
pmap_dfr(df, ~ f(..1, ..2, ..3))
# A tibble: 52 x 3
# site tr year
# * <chr> <int> <int>
# 1 a 1 1
# 2 a 2 1
# 3 a 3 1
# 4 a 1 2
# 5 a 2 2
# 6 a 3 2
# 7 a 1 3
# 8 a 2 3
# 9 a 3 3
#10 a 1 4
# … with 42 more rows
另一个选项是来自 dplyr
开发版本的 condense
library(tidyr)
df %>%
group_by(rn = row_number()) %>%
condense(out = f(site, years, tr)) %>%
unnest(c(out))
或者在base R
中,我们也可以将do.call
与Map
一起使用
do.call(rbind, do.call(Map, c(f, unname(as.data.frame(df)))))
关于r - 如何在数据帧上按行应用函数以在 r 中生成新的或扩展的数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60555278/