[英]r: iterating through all elements of several columns to detect a phrase
我正在嘗試遍歷包含文本文件的數據框中的幾列。
我想檢查第 7 列到第 16 列的每個條目,以查看是否有任何文本文件包含某個短語。
每次檢測到短語時,我想將它出現的次數增加 1。
這看起來很簡單。 我想我應該遍歷列和行,但我似乎無法確切地弄清楚如何做到這一點。
有什么建議? 提前感謝您的任何見解。
fc_count <- 0
for (col in profiles[7:16]){
for (row in 1:nrow(profiles)){
if(isTRUE(grepl("my name is jeff", row)) == TRUE){
fc_count = fc_count + 1
}
}
}
fc_count
我們可以使用lapply
循環第 7 到 16 列,應用grepl
,使用pattern
來獲取邏輯向量list
, Reduce
,通過添加 ( +
) 將其轉換為單個整數向量,然后通過sum
獲得sum
sum(Reduce(`+`, lapply(profiles[7:16], grepl, pattern = "my name is jeff")))
由於grepl
被vector
grepl
vector
,如果我們將 'data.frame' 轉換為matrix
( matrix
是具有暗淡屬性的向量),它會更緊湊
sum(grepl("my name is jeff", as.matrix(profiles[7:16])))
此外,對於for
循環,我們不需要嵌套循環,因為grepl
是矢量化的
fc_count <- 0
for(prf in profiles[7:16]){
fc_count <- fc_count + sum(grepl("my name is jeff", prf))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.