【问题标题】:lookup data in a datatable and add it to a new column在数据表中查找数据并将其添加到新列
【发布时间】:2016-04-13 12:48:23
【问题描述】:

我有两个数据表如下图:
bigrams

 w1w2           freq   w1          w2      
 common names   1      common      names  
 department of  4      department  of  
 family name    6      family      name  

bigrams = setDT(structure(list(w1w2 = c("common names", "department of", "family name"
), freq = c(1L, 4L, 6L), w1 = c("common", "department", "family"
), w2 = c("names", "of", "name")), .Names = c("w1w2", "freq", 
"w1", "w2"), row.names = c(NA, -3L), class = "data.frame"))

一元组

w1            freq  
common        2  
department    3  
family        4  
name          5  
names         1  
of            9  

unigrams = setDT(structure(list(w1 = c("common", "department", "family", "name", 
"names", "of"), freq = c(2L, 3L, 4L, 5L, 1L, 9L)), .Names = c("w1", 
"freq"), row.names = c(NA, -6L), class = "data.frame"))

想要的输出

 w1w2           freq   w1          w2      w1freq    w2freq  
 common names   1      common      names   2         1
 department of  4      department  of      3         9
 family name    6      family      name    4         5

到目前为止我做了什么

setkey(bigrams, w1)
setkey(unigrams, w1)
result <- bigrams[unigrams]

这给了我w1i.freq 列,但是当我尝试对w2 执行相同操作时,i.freq 列会更新以反映w2 的频率。

如何在不同的列中同时获取 w1w2 的频率?

注意:我已经看到data.table Lookup value and translateModify column of a data.table based on another column and add the new column 的解决方案

【问题讨论】:

  • 您在寻找 data.table 解决方案吗?否则这应该工作: bigrams$w1freq
  • @chinsoon12 是的,我更愿意使用 data.table 来解决它,因为我计划将解决方案用于更大的数据集。
  • 您想要的输出中的freq 列是否正确?
  • @Symbolix 不是,但我已经更正了,谢谢
  • 这么想 - 现在我的解决方案很有意义:)

标签: r data.table


【解决方案1】:

您可以进行两次连接,在 v1.9.6 的 data.table 中,您可以为不同的列名指定 on= 参数。

library(data.table)

bigrams[unigrams, on=c("w1"), nomatch = 0][unigrams, on=c(w2 = "w1"), nomatch = 0]

            w1w2 freq         w1    w2 i.freq i.freq.1
1:   family name    6     family  name      4        5
2:  common names    1     common names      2        1
3: department of    4 department    of      3        9

【讨论】:

    【解决方案2】:

    你可以通过一些重塑来做到这一点。

    library(dplyr)
    library(tidyr)
    
    bigrams %>%
      rename(w1w2_string = w1w2,
             w1w2_freq = freq) %>%
      gather(order, string,
             w1, w2) %>%
      left_join(unigrams %>%
                  rename(string = w1) ) %>%
      gather(type, value,
             string, freq) %>%
      unite(order_type, order, type) %>%
      spread(order_type, value)
    

    编辑:解释

    您可以做出的第一个观察是,二元组实际上包含有关三种不同分析单位的信息:一个二元组和两个一元组。转换为长格式,以便分析单位为一元组。然后我们可以合并其他一元数据。现在请注意,您的 unigram 每行有两条不同的信息:unigram 的频率和 unigram 的文本。再次转换为长格式,以便分析单位是关于一元组的一条信息。现在展开,以便每个新列都是关于一元组的一种信息。

    【讨论】:

    • 你能解释一下解决方案吗?
    猜你喜欢
    • 2013-04-14
    • 2016-01-20
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    • 2018-08-20
    • 2023-02-24
    相关资源
    最近更新 更多