我有一个数据帧,lexicon,有650个单词,我想通过从lexicon中随机 Select 单词,为5个说话者创建一系列随机单词列表.我想在为期24个月的数据收集期间完成这项工作,每个月都会采集不同大小的词汇样本.指定月份和词汇表大小的基本数据帧为df1:

df1 <- data.frame(months=rep(1:24, times=5, each=1),
                  vocab_size=(sample(c(0:25), 120, replace=TRUE)),
                  Speaker=rep(c("A", "B", "C", "D", "E"), times=1, each=24))

list1 <- split(df1, f=df1$Speaker)

lexicon大概是这样的:

lexicon <- data.frame(c("a", "about", "above", "ain't", "all", "am", "an", "and",  
                        "animal",  "ankle", "ant" ,"any", "apple","applesauce", 
                        "asleep", "at",  "ate",  "aunt", "auntie",  "aunty's", 
                        "awake", "away", "baa", "baby" , "baby+doll", "bad" ,
                        "ball", "balloon", "banana", "basket", "bat", "bath", 
                        "bathing", "bathtub", "be", "beach", "bead", "bean",
                        "because", "bed", "beddy", "bee", "been", "behind",
                        "being", "belt", "bench", "bib", "bicycle", "big"))

在使用以下代码之后,我一直在try 生成我想要的输出:

vocab_data <- lapply(list1, FUN=function(element) {
  all_vocab <- slice_sample(lexicon, n=element$vocab_size, replace=TRUE)
})

但我收到以下错误消息

 Error in `slice_sample()`:
 ! `n` must be a constant.
 Caused by error in `element$vocab_size`:
 ! $ operator is invalid for atomic vectors

有没有办法通过这种方式从数据框中提取不同大小的样本, for each 说话者创建一个每个月的词汇表?

推荐答案

之所以会出现这个错误,是因为在本例中,slice_sample获得了一个数字向量,但它只需要一个数字n.可以使用rowwise来解决这个问题,它分别处理每一行,因此slice_sample只能看到一个数字.

library(dplyr)

df1 %>% 
  rowwise() %>% 
  mutate(all_vocab = list(slice_sample(lexicon, n=vocab_size))) %>% 
  ungroup()
# A tibble: 120 × 4
   months vocab_size Speaker all_vocab    
    <int>      <int> <chr>   <list>       
 1      1          1 A       <df [1 × 1]> 
 2      2         15 A       <df [15 × 1]>
 3      3         18 A       <df [18 × 1]>
 4      4         18 A       <df [18 × 1]>
 5      5         24 A       <df [24 × 1]>
 6      6          4 A       <df [4 × 1]> 
 7      7          3 A       <df [3 × 1]> 
 8      8         10 A       <df [10 × 1]>
 9      9         24 A       <df [24 × 1]>
10     10         19 A       <df [19 × 1]>
# ℹ 110 more rows
# ℹ Use `print(n = ...)` to see more rows

R相关问答推荐

R中具有gggplot 2的Likert图,具有不同的排名水平和显示百分比

基于不同组的列的相关性

有没有一个R函数允许你从一个数字变量中提取一个数字,而不考虑它的位置(不仅仅是第一个或最后一个数字?

手动打印线型gplot

RStudio中相关数据的分组箱形图

根据多个条件增加y轴高度以适应geom_text标签

S用事件解决物质平衡问题

在使用tidyModels和XGBoost的二进制分类机器学习任务中,所有模型都失败

R -使用矩阵reshape 列表

如何将一些单元格的内容随机 Select 到一个数据框中?

使用R将简单的JSON解析为嵌套框架

在R中的数据框上使用Apply()函数时,如何保留非数字列?

有没有办法将基于每个值中出现的两个关键字或短语的字符串向量重新编码为具有这两个值的新向量?

如何为混合模型输出绘制不同的线型?

在同一单元格中创建包含整数和百分比的交叉表

R中从因数到数字的转换

在一个multiplot中以非对称的方式在R中绘制多个图

如果y中存在x中的值,则将y行中的多个值复制到相应的x行中

如何修复geom_rect中的层错误?

如何在类应用函数中访问函数本身