在R中有没有选择最大单词的特定函数?

huangapple go评论48阅读模式
英文:

Is there any specific function to choose max words in R?

问题

以下是翻译好的内容:

Cuisines(菜肴)
1)印度、美国、日本、韩国、中国
2)地中海、欧洲、印度尼西亚
3)马来西亚、墨西哥、巴西、越南

Restaurants(餐厅)
1)A
2)B
3)C

如何找出哪家餐厅提供更多种类的菜肴?是否有相应的函数可以完成此任务?我想获取餐厅和菜肴的名称。请帮助。

我尝试使用count函数,但没有得到期望的结果。

英文:

For e.g.,

Cuisines

  1. Indian, American, Japanese, Korean, Chinese
  2. Meditterranean, Continental, Indonesian
  3. Malaysian, Mexican, Brazillian, Vietnamese

Restaurants

  1. A
  2. B
  3. C

How can I find out which restaurant serves more cuisines? Is there any function to get this done? I want to get both the restaurant's and the cuisine's names. Please help.

I tried to use the count function, but it's not showing the desired result.

答案1

得分: 1

If your data look like this:

df <- data.frame(cuisines = c("Indian, American, Japanese, Korean, Chinese",
                              "Meditterranean, Continental, Indonesian",
                              "Malaysian, Mexican, Brazillian, Vietnamese"),
                 Restaurants = LETTERS[1:3])

In base R, you can use gregexpr and \\W+ to count the words, then use which with max to index (I also added a stringr package option):

wds <- lengths(gregexpr("\\W+", df$cuisines))
# or stringr::str_count(df$cuisines, "\\S+")

df[which(wds == max(wds)), ]

#                                      cuisines Restaurants
# 1 Indian, American, Japanese, Korean, Chinese           A
英文:

If your data look like this:

df <- data.frame(cuisines = c("Indian, American, Japanese, Korean, Chinese",
                              "Meditterranean, Continental, Indonesian",
                              "Malaysian, Mexican, Brazillian, Vietnamese"),
                 Restaurants = LETTERS[1:3])

In base R, you can use gregexpr and \\W+ to count the words, then use which with max to index (I also added a stringr package option)

wds <- lengths(gregexpr("\\W+", df$cuisines))
# or stringr::str_count(df$cuisines, "\\S+")

df[which(wds == max(wds)), ]

#                                      cuisines Restaurants
# 1 Indian, American, Japanese, Korean, Chinese           A

huangapple
  • 本文由 发表于 2023年5月10日 20:11:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76218269.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定