【问题标题】:R: Add new column to dataframe using functionR:使用函数向数据框添加新列
【发布时间】:2015-04-25 08:37:53
【问题描述】:

我有一个数据框 df,它有两列,termfrequency。我还有一个具有给定 ID 的术语列表,存储在一个名为 indices 的向量中。为了说明这两个信息,我有以下内容:

> head(indices)
   Term
1    hello
256  i
33   the

同样,对于数据框。

> head(df)
   Term  Freq
1  i     24
2  hello 12
3  the   28

我想在df 中添加一个名为TermID 的列,这将只是向量indices 中术语的索引。我曾尝试使用dplyr::mutate,但无济于事。下面是我的代码

library(dplyr)

whichindex <- function(term){
              ind <- which(indices == as.character(term))
              ind}

mutate(df, TermID = whichindex(Term))

我得到的输出是一个df,它有一个名为TermID 的新列,但TermID 的所有值都是相同的。

谁能帮我弄清楚我做错了什么?如果您可以在 [R] 中推荐一种更有效的算法来执行此操作,那也很好。我已经在 Python 中实现了这个,我还没有遇到过这样的问题。

提前致谢。

【问题讨论】:

  • 为什么不只是merge(来自基地)或join
  • 另外,您能否发布dput(head(indices))dput(head(df)) 的输出,以免您使用的数据结构有歧义。
  • 谢谢,阿难。因为我要处理几十万字,所以我实际上正在寻找一种更快的算法。 dfindices 都有 class = "data.frame"。但是,我注意到indicesTerm 列下的每个元素都是class = "factor"
  • df$TermID &lt;- match(df$Term,indices$Term) 会做到这一点,根据我的测试,在一百万个案例中将花费几毫秒。
  • @thelatemail 做到了。谢谢。

标签: r dplyr


【解决方案1】:

怎么样?

df %>% rowwise() %>% mutate(TermID = grep(Term,indices))

带有示例数据:

library(dplyr)
indices <- c("hello","i","the")
df <- data_frame(Term = c("i","hello","the"), Freq = c(24,12,28))

df_res <- df %>% rowwise() %>% mutate(TermID = grep(Term,indices))
df_res

给出:

Source: local data frame [3 x 3]
Groups: <by row>

   Term Freq TermID
1     i   24      2
2 hello   12      1
3   the   28      3

【讨论】:

  • 我执行了这个建议,没有收到任何错误。但是,生成的 df 保持不变(没有额外的 TermID 列)。一定是数据结构的原因。让我再次检查以找到一些答案。
  • @EFL df 保持不变,您必须将输出绑定到变量,如上例中的df_res。这有助于回答您的问题吗?如果不能随意发布您自己的答案并接受,否则。
  • 这里的rowwise有什么用?我试过没有按行,它工作。
猜你喜欢
  • 2018-02-09
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
  • 1970-01-01
  • 2023-01-29
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多