【发布时间】:2020-06-18 16:05:26
【问题描述】:
我正在尝试扩展现有数据集,目前看起来像这样:
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
如何将函数应用于输入数据帧的每一行以生成最终数据帧? base r 中的 apply 函数之一或 purrr 包中的 pmap_df() 似乎很理想,但由于不熟悉这些函数的工作原理,我所有的努力都只产生了错误。
【问题讨论】:
标签: r function tidyverse rowwise