假设我有两个数据框,学生和老师.
students <- data.frame(name = c("John", "Mary", "Sue", "Mark", "Gordy", "Joey", "Marge", "Sheev", "Lisa"),
height = c(111, 93, 99, 107, 100, 123, 104, 80, 95),
smart = c("no", "no", "yes", "no", "yes", "yes", "no", "yes", "no"))
teachers <- data.frame(name = c("Ben", "Craig", "Mindy"),
height = c(130, 101, 105),
smart = c("yes", "yes", "yes"))
Run Code Online (Sandbox Code Playgroud)
我希望生成所有可能的学生和教师组合并保留随附的信息,基本上创建数据框"学生"和"教师"的所有行组合.这可以通过循环和cbind轻松完成,但对于大型数据帧,这需要永远.帮助一个R新手 - 最快的方法是什么?
编辑:如果这不清楚,我希望输出具有以下格式:
rbind(
cbind(students[1, ], teachers[1, ]),
cbind(students[1, ], teachers[2, ])
...
cbind(students[n, ], teachers[n, ]))
Run Code Online (Sandbox Code Playgroud)
您可以将所有数据合并如下:
do.call(cbind.data.frame,Map(expand.grid,teacher=teachers,students=students))
name.teacher name.students height.teacher height.students smart.teacher smart.students
1 Ben John 130 111 yes no
2 Craig John 101 111 yes no
3 Mindy John 105 111 yes no
4 Ben Mary 130 93 yes no
5 Craig Mary 101 93 yes no
6 Mindy Mary 105 93 yes no
: : : : : : :
: : : : : : :
Run Code Online (Sandbox Code Playgroud)