I have a tibble with variables/columns that include lists of tibbles of differing shapes. I would like to add a variable/column to each (sub-)tibble in one of the variables.
E.g. such data
library("tibble")
aaa <- tibble(qq = c(1,2,3),
ww = list(tibble(a = c(1,2), s = c("as", "df")),
tibble(a = 3, s ="q"),
tibble(a = 4, s = "e")),
ee = list(tibble(a = c(1,2), s = c("as", "df")),
tibble(a = c(3,6), s = c("qz", "wz")),
tibble(a = 4, s = "ez")))
Which look like:
> aaa
# A tibble: 3 x 3
qq ww ee
<dbl> <list> <list>
1 1.00 <tibble [2 × 2]> <tibble [2 × 2]>
2 2.00 <tibble [1 × 2]> <tibble [2 × 2]>
3 3.00 <tibble [1 × 2]> <tibble [1 × 2]>
and
> aaa$ee
[[1]]
# A tibble: 2 x 2
a s
<dbl> <chr>
1 1.00 as
2 2.00 df
[[2]]
# A tibble: 2 x 2
a s
<dbl> <chr>
1 3.00 qz
2 6.00 wz
[[3]]
# A tibble: 1 x 2
a s
<dbl> <chr>
1 4.00 ez
Let's say I want to create a new variable in each tibble in aaa$ee called lll, which is the first letter of each string in variable s in that table.
I can get these with lapply, e.g.:
lll <- lapply(X = aaa$ee,
FUN = function(z){substr(z$s, 1,1)})
Resulting in
> lll
[[1]]
[1] "a" "d"
[[2]]
[1] "q" "w"
[[3]]
[1] "e"
But how do I bind each vector in this list as a column in each tibble in aaa$ee?
To produce a result that should look something like
> aaa$ee
[[1]]
# A tibble: 2 x 2
a s
<dbl> <chr> <chr>
1 1.00 as a
2 2.00 df d
[[2]]
# A tibble: 2 x 2
a s
<dbl> <chr> <chr>
1 3.00 qz q
2 6.00 wz w
[[3]]
# A tibble: 1 x 2
a s
<dbl> <chr> <chr>
1 4.00 ez e
We can loop through the 'ee' column with map and mutate to create the 'new' column
library(purrr)
out <- aaa %>%
mutate(ee = map(ee, ~ .x %>%
mutate(new = substr(s, 1, 1))))
out$ee
#[[1]]
## A tibble: 2 x 3
# a s new
# <dbl> <chr> <chr>
#1 1 as a
#2 2 df d
#[[2]]
# A tibble: 2 x 3
# a s new
# <dbl> <chr> <chr>
#1 3 qz q
#2 6 wz w
#[[3]]
# A tibble: 1 x 3
# a s new
# <dbl> <chr> <chr>
#1 4 ez e
If we are using the lapply method (using base R), then with transform create a new column and assign it to the 'ee'
aaa$ee <- lapply(aaa$ee, transform, new = substr(s, 1, 1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With