I'm trying to mutate a new variable in a nested dataframe with an ifelse-condition. But the problem is that after implementing the ifelse-condition the nested dataframe turns into a list.
I want to show this problem with the iris dataset:
Here you can see the original nested format:
iris %>% nest(data = -Species)
# A tibble: 3 x 2
Species data
<fct> <list>
1 setosa <tibble [50 x 4]>
2 versicolor <tibble [50 x 4]>
3 virginica <tibble [50 x 4]>
And now I want to mutate a new variable in the nested dataframes:
iris %>%
nest(data = -Species) %>%
mutate(data = map(data, function(x)
x %>% mutate(`Sepal.Length^2` = Sepal.Length^2)))
# A tibble: 3 x 2
Species data
<fct> <list>
1 setosa <tibble [50 x 5]>
2 versicolor <tibble [50 x 5]>
3 virginica <tibble [50 x 5]>
This code works. The data-column is as desired in the tibble-format.
But if I insert the ifelse-condition now, the tibble-format is lost:
iris %>%
nest(data = -Species) %>%
mutate(data = map(data, function(x)
ifelse(!is.na(x), x %>% mutate(`Sepal.Length^2` = Sepal.Length^2), NA)))
# A tibble: 3 x 2
Species data
<fct> <list>
1 setosa <list [200]>
2 versicolor <list [200]>
3 virginica <list [200]>
I want to keep the tibble-format even with the ifelse-condition.
Can anyone help me?