Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list variable with mutate in R

Tags:

list

r

dplyr

I want to use mutate to create a list variable/column in a dataframe (actually, a tibble). Here is a simplified version of my problem:

Y = c(12,10,15)
df = tibble(z=seq(1,20)) %>% mutate( zz = ifelse(z>Y,z,Y) )

In other words, the variable zz in df must contain a list of 3 values where each value of Y is replaced by z if and only if z>Y. However, mutate does not produce a column of 3-element lists. It gives me a warning and produces a vector of 60 elements.

like image 755
Massimo2013 Avatar asked Feb 25 '26 21:02

Massimo2013


1 Answers

You need to combine mutate with map and pmax is less verbose than if_else:

df <- df %>%
  mutate(zz = map(z, ~pmax(.x, Y)))
like image 98
r.user.05apr Avatar answered Feb 28 '26 11:02

r.user.05apr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!