首页 > 解决方案 > 如何计算一列中有多少个字符串

问题描述

我有一个包含“便利设施”列的数据集,我想计算每行有多少便利设施。

> airbnbT$amenities[1]
[1] ["Essentials", "Refrigerator", "Shampoo", "TV", "Dedicated workspace", "Hangers", "Iron", "Long term stays allowed", "Dishes and silverware", "First aid kit", "Free parking on premises", "Hair dryer", "Patio or balcony", "Washer", "Dryer", "Cooking basics", "Coffee maker", "Private entrance", "Hot water", "Fire extinguisher", "Wifi", "Air conditioning", "Hot tub", "Kitchen", "Microwave", "Oven", "Smoke alarm"]
14673 Levels: ["Air conditioning", "Baby bath", "Long term stays allowed", "Baby monitor"] ...

> class(airbnbT$amenities[1])
[1] "factor"

第 1 排有 27 个便利设施。有没有办法计算每一行中的逗号 "," ?这种方式将计算便利设施的数量。

标签: rstring

解决方案


Try str_count from the stringr package. You will need to add 1 since there will be one fewer comma than the number of amenities:

library(stringr)

airbnbT$amenities_count = str_count(airbnbT$amenities,",") + 1


推荐阅读