首页 > 解决方案 > 每个新行的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 等)?

标签: rloopssample

解决方案


添加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

推荐阅读