如何从列表中随机选择问题?

时间:2019-08-22 13:27:34

标签: r

我已经制定了测验的问题和答案。这是一个包含50多个问题的列表。现在,我需要从列表中随机选择问题。选择应基于主题,技能级别和难度级别(在列表中称为差异)。

由于我是新手程序员,所以详细的解释将帮助我发展技能。

预先感谢

这是一个示例问题:

new <- list(question="What is name of the tallest building in the world?", 
    answers=list(
      c("(a) Empire state",0),
      c("(b) Shanghai Tower",0),
      c("(c) Abraj Al-Bait Clock Tower",0),
      c("(d) Burj Khalifa",1),
      c("(e) None of the above",0)),
    diff=NA,
    topic='General Knowledge',
    skill=NA,
    using=TRUE,
    id=10
),

2 个答案:

答案 0 :(得分:1)

如果您只想从列表中选择一个任意条目,则可以使用以下命令,其中question_list是问题列表。 sample()函数正在从1到Question_list的长度之间选择一个随机整数,而[]在列表中调用该结果。

question_list[sample(1:length(question_list),1)]

答案 1 :(得分:0)

您可以使用以下代码根据条件进行随机选择。

# Create sample data frame
df <- data.frame(
  question = c("What is", "Who is", "Where is"),
  answera = c("i", "j", "k"),
  answerb = c("l", "m", "n"),
  answerc = c("o", "p", "q"),
  topic = c("geography", "geography", "history"),
  skill = c("low", "high", "high")
  )

# Option 1 - Filter list based on topic and skill
subset(df, select = c('question','answera','answerb','answerc'), topic == 'geography' & skill == 'low')

# Option 2 - Randomly select two questions
df[sample(nrow(df), 2), ]

# Option 3 - Filter and then randomly select
filtered <- subset(df, select = c('question','answera','answerb','answerc'), topic == 'geography')
filtered[sample(nrow(filtered ), 1), ]