修改/添加列到嵌套的tibble

时间:2018-05-02 02:25:37

标签: r nested tibble

我有一个包含变量/列的元组,其中包含不同形状的元组列表。我想在其中一个变量中为每个(子)tibble添加一个变量/列。

E.g。这样的数据

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

看起来像:

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

> 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   

我想说我想在名为tibble的{​​{1}}中的每个aaa$ee中创建一个新变量,这是变量{{1}中每个字符串的第一个字母在那张桌子里。

我可以使用lll来获取这些内容,例如:

s

导致

lapply

但是如何将此列表中的每个向量绑定为lll <- lapply(X = aaa$ee, FUN = function(z){substr(z$s, 1,1)}) 中每个> lll [[1]] [1] "a" "d" [[2]] [1] "q" "w" [[3]] [1] "e" 的列?

生成看起来像

的结果
tibble

1 个答案:

答案 0 :(得分:3)

我们可以使用# Skip lines 3 and 4 if not using virtualenv. # At command prompt mkdir django1 cd django1 virtualenv venv source venv/bin/activate pip install django==1.11 django-admin startproject django1 . # run the Django shell python manage.py shell # paste into shell following: from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False, ) # This should write an email like the following: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Subject here From: from@example.com To: to@example.com Date: Wed, 02 May 2018 02:12:09 -0000 Message-ID: <20180502021209.32641.51865@i1022> Here is the message. public void GenerateForm<T>(T form) { if (form.GetType() == typeof(Form1)) { Console.WriteLine(((Form1)(object)form).name); } } 遍历“ee”列以创建“新”列

map

如果我们使用mutate方法(使用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 ),则使用lapply创建新列并将其分配给'ee'

base R