计算R中多列中的特定单词

编程入门 行业动态 更新时间:2024-10-23 05:47:08
本文介绍了计算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中多列中的特定单词

本文发布于:2023-10-28 19:34:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1537583.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单词   中多列中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!