【问题标题】:Taking values from a dataframe to loop for operations into another dataframe从数据帧中获取值以循环操作到另一个数据帧
【发布时间】:2019-02-22 15:37:44
【问题描述】:
vocab
 wordIDx V1
    1  archive
    2  name
    3  atheism
    4  resources
    5  alt

wordIDx newsgroup_ID    docIdx  word/doc    totalwords/doc totalwords/newsgroup wordID/newsgroup    P(W_j)
1   1   196 3   1240    47821   2   0.028130269
1   1   47  2   1220    47821   2   0.028130269
2   12  4437    1   702 47490   8   0.8
3   12  4434    1   673 47490   8   0.035051912
5   12  4398    1   53  47490   8   0.4
3   12  4564    11  1539    47490   8   0.035051912

对于 vocab 中的每个 wordIDx,我需要计算以下公式: 例如 wordIDx = 1 ; 我的价值应该是

max(log(0.02813027)+sum(log(2/47821),log(2/47821)))
= -23.73506

我现在有以下代码:

 classifier_3$ans<- max(log(classifier_3$`P(W_j)`)+ (sum(log(classifier_3$`wordID/newsgroup`/classifier_3$`totalwords/newsgroup`))))

如何以一种考虑 vocab 数据帧中的所有 wordIDx 并计算上述示例的方式循环,正如我突出显示的那样。

【问题讨论】:

  • 您能否通过 dput(head(dataframe, 10)) 提供您的示例数据?

标签: r loops dataframe


【解决方案1】:

类似这样,但您确实需要清理列名。

vocab <- read.table(text = "wordIDx V1
1  archive
2  name
3  atheism
4  resources
5  alt", header = TRUE, stringsAsFactors = FALSE)

classifier_3 <- read.table(text = "wordIDx newsgroup_ID    docIdx  word/doc            totalwords/doc totalwords/newsgroup wordID/newsgroup    P(W_j)
1   1   196 3   1240    47821   2   0.028130269
1   1   47  2   1220    47821   2   0.028130269
2   12  4437    1   702 47490   8   0.8
3   12  4434    1   673 47490   8   0.035051912
5   12  4398    1   53  47490   8   0.4
3   12  4564    11  1539    47490   8   0.035051912", header = TRUE, stringsAsFactors = FALSE)

classifier_3 <- classifier_3[!duplicated(classifier_3$wordIDx), ]
classifier_3 <- merge(vocab, classifier_3, by = c("wordIDx"))
classifier_3$ans<- pmax(log(classifier_3$`P.W_j.`)+ 
                     (log(classifier_3$`wordID.newsgroup`/classifier_3$`totalwords.newsgroup`) +
                            # isn't that times 2?
                            log(classifier_3$`wordID.newsgroup`/classifier_3$`totalwords.newsgroup`)),
                        log(classifier_3$`wordID.newsgroup`/classifier_3$`totalwords.newsgroup`))

【讨论】:

  • classifier_3
  • 可以使用classifier_3 &lt;- merge(classifier_3, vocab, by = "wordIDx", all.x = TRUE)进行合并。
  • 它有效。但是,我需要遍历所有 wordID 并找到 max(log(P(w_j)) + sum(所有 docIDx 都存在 wordID 的所有行)的 ans。 . 我不知道如何编辑第三行。感谢您的指导。
  • pmaxmax 的并行版本,它适用于列。计算你想要最大值的 2 列作为中间结果,然后应用 pmax。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 2022-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
相关资源
最近更新 更多