简体   繁体   中英

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))

result:

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

Is it possible to map the function by using the elements within the same dataframe?

In your context x$period is NULL since x is the list of dataframes and it has no attribute "period". I think you want to access the period column within each unnammed dataframe in the list. I would just use map which will pass along each dataframe in the list, which you can then manipulate in the function to access each column without having to explicitly pass it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM