2016-05-12 49 views
1

我有一个数据帧,有很多卦和它们的频率。从数据帧中的行中删除单词

如何添加第三列(我们称之为finalWord),其中只显示trigram的最后一个单词?

下面是数据帧的例子:

x <- data.frame(trigrams = c("I have to", "I need to"), freq = c(10, 7)) 

输出应该是:

x <- data.frame(trigrams = c("I have to", "I need to"), freq = c(10, 7), finalWord = c("to", "to")) 

回答

1

我们可以使用sub

x$finalword <- sub(".*\\s+", '', x$trigrams) 
x$finalword 
#[1] "to" "to" 

library(stringi) 
stri_extract_last(x$trigrams, regex="\\w+")