英文:
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
- Indian, American, Japanese, Korean, Chinese
- Meditterranean, Continental, Indonesian
- Malaysian, Mexican, Brazillian, Vietnamese
Restaurants
- A
- B
- 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论