计算R中多列中的特定单词 [英] counting specific words across multiple columns in R

查看:94
本文介绍了计算R中多列中的特定单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据帧

I have a data frame like this

df <- data.frame(id=c(1, 2, 3, 4, 5), staple_1=c("potato", "cassava","rice","fruit","coffee"), staple_2=c("cassava","beer","peanuts","rice","yams"), staple_3=c("rice","peanuts","fruit","fruit","rice"))

我也有这样的字符向量

staples<-c("potato","cassava","rice","yams")

我想创建一个新的变量,它是装订字符向量中任何单词出现的行总和。其结果应如下所示:

I would like to create a new variable that is the row sum of the occurrence of any of the words in the "staples" character vector. The outcome of which should look like this

df$staples<-c(3,1,1,1,2)

我尝试了几种方法,但到目前为止没有任何效果。我的实际数据框更大,并且字符向量中包含20个或更多的单词。我敢肯定有一个简单的解决方案,但是我不知何故会错过它。

I have tried several approaches and nothing has worked so far. My actual dataframe is much bigger and character vector has 20 or more words in it. I'm sure there is a simple solution but that I am missing it somehow.

推荐答案

简单的应用即可实现。

apply(df, 1, function(x) sum(staples %in% x))
#[1] 3 1 1 1 2

df$staples <- apply(df, 1, function(x) sum(staples %in% x))

这篇关于计算R中多列中的特定单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆