R:使用函数将新列添加到数据框
R: Add new column to dataframe using function
我有一个数据框 df
,它有两列,term 和 frequency。我还有一个带有给定 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中实现了这个,我没有遇到过这样的问题。
提前致谢。
怎么样?
df %>% rowwise() %>% mutate(TermID = grep(Term,indices))
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
给出:
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
,它有两列,term 和 frequency。我还有一个带有给定 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中实现了这个,我没有遇到过这样的问题。
提前致谢。
怎么样?
df %>% rowwise() %>% mutate(TermID = grep(Term,indices))
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
给出:
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