问题描述
我仍在学习 R 语言,我的任务是根据另一个变量将一长串学生分成四人一组.我已将数据作为数据框加载到 R 中.如何在不替换的情况下对整行进行采样,从变量的 4 个级别中的每一个级别中抽取一个,并让 R 将数据输出到电子表格中?
I'm still learning R and have been given the task of grouping a long list of students into groups of four based on another variable. I have loaded the data into R as a data frame. How do I sample entire rows without replacement, one from each of 4 levels of a variable and have R output the data into a spreadsheet?
到目前为止,我一直在修改 for 循环和示例函数,但我很快就忘记了.有什么建议么?这是我正在尝试做的示例.鉴于:
So far I have been tinkering with a for loop and the sample function but I'm quickly getting over my head. Any suggestions? Here is sample of what I'm attempting to do. Given:
Last.Name <- c("Picard","Troi","Riker","La Forge", "Yar", "Crusher", "Crusher", "Data")
First.Name <- c("Jean-Luc", "Deanna", "William", "Geordi", "Tasha", "Beverly", "Wesley", "Data")
Email <- c("a@a.com","b@b.com", "c@c.com", "d@d.com", "e@e.com", "f@f.com", "g@g.com", "h@h.com")
Section <- c(1,1,2,2,3,3,4,4)
df <- data.frame(Last.Name,First.Name,Email,Section)
我想从每个部分随机选择一个《星际迷航》角色,最后得到 2 组,每组 4 个.我希望将整行的信息价值转移到包含所有组及其相应组号的新数据框中.
I want to randomly select a Star Trek character from each section and end up with 2 groups of 4. I would want the entire row's worth of information to make it over to a new data frame containing all groups with their corresponding group number.
推荐答案
我会使用很棒的包 'dplyr'
I'd use the wonderful package 'dplyr'
require(dplyr)
random_4 <- df %>% group_by(Section) %>% slice(sample(c(1,2),1))
random_4
Source: local data frame [4 x 4]
Groups: Section
Last.Name First.Name Email Section
1 Troi Deanna b@b.com 1
2 La Forge Geordi d@d.com 2
3 Crusher Beverly f@f.com 3
4 Data Data h@h.com 4
random_4
Source: local data frame [4 x 4]
Groups: Section
Last.Name First.Name Email Section
1 Picard Jean-Luc a@a.com 1
2 Riker William c@c.com 2
3 Crusher Beverly f@f.com 3
4 Data Data h@h.com 4
%>% 表示然后"
代码读作:
取 DF 然后为所有部分",按位置(切片)1 或 2 选择.瞧.
Take DF AND THEN for all 'Section', select by position (slice) 1 or 2. Voila.
这篇关于使用 R,将学生随机分配到 4 人一组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!