R语言结合不同的表

时间:2017-07-13 05:31:25

标签: r dplyr

我有一张桌子

grade       gradepoint
  o             10
  A              9
  B              8

我有第二张表

subjectname       credits
  englishI          3
   mI               3
   AC Lab           2

我有第三张表,其中包含不同科目的成绩,例如

rollno     englishI        mI             ACLab
  1           A            B               o
  2           B            B               o

现在我需要一个包含第三个表中每列的子列的表

rollno      englishI                        mI                    ACLab         
         grade   gradepoint Credits  grade  gradepoint Credit   grade gradepoint credit 
1           A      9           3      B       8          3       o      10                                             2
2           B      8           3      B       8          3       o      10                     2

如何将这些数据框合并到一个数据框中以及如何访问列中的子列

1 个答案:

答案 0 :(得分:0)

使用dplyrtidyr的解决方案。请注意,在数据框中,类似注释提到的子列不受支持,因此我为每列创建了组合列名,例如englishI_creditsdt4是最终输出。

# Load package
library(dplyr)
library(tidyr)

# Create table 1
df1 <- read.table(text = "grade       gradepoint
  o             10
                  A              9
                  B              8",
                  header = TRUE, stringsAsFactors = FALSE)

# Create table 2
df2 <- read.table(text = "subjectname       credits
  englishI          3
                  mI               3
                  ACLab            2",
                  header = TRUE, stringsAsFactors = FALSE)

# Create table 3
df3 <- read.table(text = "rollno     englishI        mI             ACLab
  1           A            B               o
                  2           B            B               o",
                  header = TRUE, stringsAsFactors = FALSE)

# Process the data
df4 <- df3 %>%
  gather(subjectname, grade, -rollno) %>%
  left_join(df1, by = "grade") %>%
  left_join(df2, by = "subjectname") %>%
  gather(info, value, grade:credits) %>%
  unite(item, subjectname, info) %>%
  spread(item, value) %>%
  # Convert character numbers to numeric
  mutate_if(function(Col){all(!grepl("\\D", Col))}, as.numeric)