Massimo2013
Massimo2013

Reputation: 593

Create a list variable with mutate in R

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.

Upvotes: 3

Views: 1444

Answers (1)

r.user.05apr
r.user.05apr

Reputation: 5456

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

df <- df %>%
  mutate(zz = map(z, ~pmax(.x, Y)))

Upvotes: 2

Related Questions