我有一个数据框df
,有两列,术语和频率.我还有一个术语列表,其中给定的ID存储在一个名为的向量中indices
.为了说明这两个信息,我有以下内容:
> head(indices)
Term
1 hello
256 i
33 the
Run Code Online (Sandbox Code Playgroud)
此外,对于数据框.
> head(df)
Term Freq
1 i 24
2 hello 12
3 the 28
Run Code Online (Sandbox Code Playgroud)
我想在df
被调用中添加一个列,TermID
它只是向量中术语的索引indices
.我尝试过使用dplyr::mutate
但无济于事.这是我的代码如下
library(dplyr)
whichindex <- function(term){
ind <- which(indices == as.character(term))
ind}
mutate(df, TermID = whichindex(Term))
Run Code Online (Sandbox Code Playgroud)
我得到的输出是一个df
有一个新列的名称TermID
,但所有的值TermID
都是相同的.
有人能帮我弄清楚我做错了什么吗?如果你能在[R]中推荐一种更有效的算法,那也很不错.我已经用Python实现了这个,我没有遇到过这样的问题.
提前致谢.
关于什么?
df %>% rowwise() %>% mutate(TermID = grep(Term,indices))
Run Code Online (Sandbox Code Playgroud)
w /示例数据:
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
Run Code Online (Sandbox Code Playgroud)
得到:
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
Run Code Online (Sandbox Code Playgroud)