本文介绍了计算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中多列中的特定单词
发布评论