簡體   English   中英

是否可以通過使用 r 中相同 dataframe 中的元素來 purrr::map function?

[英]Is it possible to purrr::map the function by using the elements within the same dataframe in r?

x = list(data.frame(age = c(1:4),period = c(2000:2003)),
         data.frame(age = c(5:8),period = c(1998:2001)),
         data.frame(age = c(11:19),period = c(1990:1998)))

map2(x, x$period, ~cbind(.x, difference = .y-.x$age))

結果:

> map2(x, x$period, ~cbind(.x, difference = .y-.x$age))
list()

是否可以通過使用同一個 dataframe 中的元素來 map function?

在您的上下文中, x$period是 NULL,因為 x 是數據幀列表並且它沒有屬性“period”。 我認為您想訪問列表中每個未命名的 dataframe 中的期間列。 我只使用map ,它將傳遞列表中的每個 dataframe,然后您可以在 function 中操作以訪問每一列,而無需顯式傳遞它。

library(purrr)
library(dplyr)

x = list(data.frame(age = c(1:4),period = c(2000:2003)),
         data.frame(age = c(5:8),period = c(1998:2001)),
         data.frame(age = c(11:19),period = c(1990:1998)))

#Original attempt
result <- map2(x, x$period, ~cbind(.x, difference = .y-.x$age))
result
#> list()

#My solution
result2 <- map(x, function(df) cbind(df, difference = df$period - df$age))
result2
#> [[1]]
#>   age period difference
#> 1   1   2000       1999
#> 2   2   2001       1999
#> 3   3   2002       1999
#> 4   4   2003       1999
#> 
#> [[2]]
#>   age period difference
#> 1   5   1998       1993
#> 2   6   1999       1993
#> 3   7   2000       1993
#> 4   8   2001       1993
#> 
#> [[3]]
#>   age period difference
#> 1  11   1990       1979
#> 2  12   1991       1979
#> 3  13   1992       1979
#> 4  14   1993       1979
#> 5  15   1994       1979
#> 6  16   1995       1979
#> 7  17   1996       1979
#> 8  18   1997       1979
#> 9  19   1998       1979

#A more readable solution using dplyr
result3 <- map(x, function(df) df %>% mutate(difference = period - age))
result3
#> [[1]]
#>   age period difference
#> 1   1   2000       1999
#> 2   2   2001       1999
#> 3   3   2002       1999
#> 4   4   2003       1999
#> 
#> [[2]]
#>   age period difference
#> 1   5   1998       1993
#> 2   6   1999       1993
#> 3   7   2000       1993
#> 4   8   2001       1993
#> 
#> [[3]]
#>   age period difference
#> 1  11   1990       1979
#> 2  12   1991       1979
#> 3  13   1992       1979
#> 4  14   1993       1979
#> 5  15   1994       1979
#> 6  16   1995       1979
#> 7  17   1996       1979
#> 8  18   1997       1979
#> 9  19   1998       1979
Created on 2023-02-02 with reprex v2.0.2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM