r - 每个新行的R循环`sample()`函数
问题描述
library(tidyverse)
fruit %>%
as_tibble() %>%
transmute(fruit = value, fruit.abr = substring(value, 1, sample(3:6, 1)))
#> # A tibble: 80 x 2
#> fruit fruit.abr
#> <chr> <chr>
#> 1 apple app
#> 2 apricot apr
#> 3 avocado avo
#> 4 banana ban
#> 5 bell pepper bel
#> 6 bilberry bil
#> 7 blackberry bla
#> 8 blackcurrant bla
#> 9 blood orange blo
#> 10 blueberry blu
#> # ... with 70 more rows
我希望我的缩写水果列是 3 到 6 个字符之间的随机字符串长度。每行将是不同的字符串长度(3 到 6 之间)。
我编写代码的方式是选择一次 3 到 6 之间的样本,然后将其用于每一行。我如何“回收”或“循环”此sample()
函数以使其为每一行选择一个新值(例如 3、6、4、3、5 等)?
解决方案
添加rowwise()
fruit %>%
as_tibble() %>%
rowwise() %>%
transmute(fruit = value, fruit.abr = substring(value, 1, sample(3:6, 1)))
# A tibble: 80 x 2
# Rowwise:
fruit fruit.abr
<chr> <chr>
1 apple apple
2 apricot apri
3 avocado avocad
4 banana bana
5 bell pepper bell
6 bilberry bil
7 blackberry black
8 blackcurrant bla
9 blood orange blo
10 blueberry blu
# ... with 70 more rows
推荐阅读
- c# - 如何将“int”数据类型项转换为“字符串”并在 LINQ 中使用“包含”在字符串列表中搜索?
- sdk - roslaunch激活失败怎么办?
- django - django rest框架在序列化程序创建方法中获取请求
- c++ - 为什么我无法使用 turbo c++ 在文件中保存多个记录(二进制模式)?
- voip - 如何使用 tshark 获得 RTP pcap 的抖动、丢包等图形视图?
- google-apps-script - 我无法为 gmail 插件安装头版应用程序
- regex - 正则表达式匹配 html 元素对
- rabbitmq - 处理 Prometheus Gauges 中的陈旧数据
- android - 如何使用 Jacoco 插件获得单元代码覆盖率和 robelectric 代码覆盖率?
- excel - 如何使用 Excel VBA 在列中的文本开头插入特定值?