背景
我撰寫了一個map2用于生成資料幀或資料幀串列的函式。我的問題是此函式生成未分配給物件的單個表。我想要的輸出是一個資料幀,它存盤矢量化回圈每次迭代的輸出小標題。
正品
df_coefs <- list()
df <-
tibble(names = c("john", "charlie", "lucy"), colours = c("green", "grey", "silver"))
funx <- function(name, colour) {
coef <- runif(1, 0, 30)
df_coefs[[i]] <-
tibble_row(names = name,
colours = colour,
coefs = coef)
}
map2(.x = df$names,
.y = df$colours,
.f = funx)
電流輸出
[[1]]
# A tibble: 1 × 3
names colours coefs
<chr> <chr> <dbl>
1 john green 11.1
[[2]]
# A tibble: 1 × 3
names colours coefs
<chr> <chr> <dbl>
1 charlie grey 3.73
[[3]]
# A tibble: 1 × 3
names colours coefs
<chr> <chr> <dbl>
1 lucy silver 29.4
期望輸出
names colours coefs
<chr> <chr> <dbl>
1 john green 11.1
2 charlie grey 3.73
3 lucy silver 29.4
uj5u.com熱心網友回復:
分配[i]似乎是一個錯字
funx <- function(name, colour) {
coef <- runif(1, 0, 30)
tibble_row(names = name,
colours = colour,
coefs = coef)
}
除此之外,如果我們需要折疊行,使用后綴_dfr中map
library(purrr)
map2_dfr(.x = df$names,
.y = df$colours,
.f = funx)
# A tibble: 3 × 3
names colours coefs
<chr> <chr> <dbl>
1 john green 14.3
2 charlie grey 25.8
3 lucy silver 13.1
uj5u.com熱心網友回復:
為什么不只是:
df <- tibble(
names = c("john", "charlie", "lucy"),
colours = c("green", "grey", "silver"),
coef = runif(3, 0, 30)
)
df
# A tibble: 3 x 3
names colours coef
<chr> <chr> <dbl>
1 john green 4.37
2 charlie grey 17.8
3 lucy silver 19.1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/347588.html
