Как удалить строки из фрейма данных, которые содержат всего несколько слов в R?

Я пытаюсь удалить из своего фрейма данных строки, содержащие менее 5 слов. например

mydf <- as.data.frame(read.xlsx("C:\\data.xlsx", 1, header=TRUE)

head(mydf)

     NO    ARTICLE
1    34    The New York Times reports a lot of words here.
2    12    Greenwire reports a lot of words.
3    31    Only three words.
4     2    The Financial Times reports a lot of words.
5     9    Greenwire short.
6    13    The New York Times reports a lot of words again.

Я хочу удалить строки с 5 или менее словами. Как я могу это сделать?


person cptn    schedule 03.03.2014    source источник


Ответы (2)


Вот два способа:

mydf[sapply(gregexpr("\\W+", mydf$ARTICLE), length) >4,]
#   NO                                          ARTICLE
# 1 34  The New York Times reports a lot of words here.
# 2 12                Greenwire reports a lot of words.
# 4  2      The Financial Times reports a lot of words.
# 6 13 The New York Times reports a lot of words again.


mydf[sapply(strsplit(as.character(mydf$ARTICLE)," "),length)>5,]
#   NO                                          ARTICLE
# 1 34  The New York Times reports a lot of words here.
# 2 12                Greenwire reports a lot of words.
# 4  2      The Financial Times reports a lot of words.
# 6 13 The New York Times reports a lot of words again.

Первый генерирует вектор, содержащий начальные позиции каждого слова после первого, а затем вычисляет длину этого вектора.

Второй разбивает столбец ARTICLE на вектор, содержащий слова-компоненты, и вычисляет длину этого вектора. Это, вероятно, лучший подход.

person jlhoward    schedule 03.03.2014

Этому также может способствовать функция подсчета слов (wc) в пакете qdap:

dat <- read.transcript(text="34    The New York Times reports a lot of words here.
12    Greenwire reports a lot of words.
31    Only three words.
2    The Financial Times reports a lot of words.
9    Greenwire short.
13    The New York Times reports a lot of words again.", 
    col.names = qcv(NO, ARTICLE), sep="   ")

library(qdap)
dat[wc(dat$ARTICLE) > 4, ]

##   NO                                          ARTICLE
## 1 34  The New York Times reports a lot of words here.
## 2 12                Greenwire reports a lot of words.
## 4  2      The Financial Times reports a lot of words.
## 6 13 The New York Times reports a lot of words again.
person Tyler Rinker    schedule 03.03.2014