r - 如何计算一列中有多少个字符串
问题描述
我有一个包含“便利设施”列的数据集,我想计算每行有多少便利设施。
> 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 个便利设施。有没有办法计算每一行中的逗号 "," ?这种方式将计算便利设施的数量。
解决方案
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
推荐阅读
- c++ - 如何在 C++ 中使用指针和数组
- windows - 如何将 HWND 转换为 SDL_Window?
- python - 从文件中读取数据,拆分单词并创建一个对象
- android - Android Studio XmlPullParser 解析多重嵌套元素
- c# - Bot Framework Cortana C# Adaptive Cards Action Buttons 不再工作
- haskell - 在 Haskell 中绘制随机游走
- jquery - 需要帮助计算数据表列的总和
- mysql - 从开始和结束时间获取行数
- python - 使用 ortools 约束求解器进行护士排班
- android - 如何在 Android 和 IOS 中获取设备 ID