Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何在不添加和删除列的情况下合并两个表_R_Dataframe_Merge_Rename - Fatal编程技术网

R 如何在不添加和删除列的情况下合并两个表

R 如何在不添加和删除列的情况下合并两个表,r,dataframe,merge,rename,R,Dataframe,Merge,Rename,我有两个表,其中包含我希望以testcase作为键连接的信息。我可以先加入它们,然后重命名列,然后对数据帧重新排序,但是还有更优雅的方法吗 df1 <- data.frame( testcase = c('testcase1', 'testcase2', 'testcase3', 'testcase4', 'testcase5'), passed = c('2', '0', '2', '0', '0'), failed = c('0', '2', '2', '0', '2

我有两个表,其中包含我希望以testcase作为键连接的信息。我可以先加入它们,然后重命名列,然后对数据帧重新排序,但是还有更优雅的方法吗


df1 <- data.frame(
  testcase = c('testcase1', 'testcase2', 'testcase3', 'testcase4', 'testcase5'), 
  passed = c('2', '0', '2', '0', '0'), 
  failed = c('0', '2', '2', '0', '2'))

df2 <- data.frame(
  id = c(1:10), testid = c('testcase3', 'testcase1', 'testcase3',   'testcase2', 'testcase5', 'testcase1', 
  'testcase3', 'testcase5', 'testcase2', 'testcase3'), total_passed = rep("", 10), total_failed= rep("", 10), testid = c(510:519), total_items = rep("", 10))



df1也许您可以借助
dplyr
库:

library(dplyr)

df2 %>%
  inner_join(df1, by = c('testid' = 'testcase')) %>%
  transmute(id, testid, total_passed = passed, total_failed = failed, 
            total_items = 10)

#   id    testid total_passed total_failed total_items
#1   1 testcase3            2            2          10
#2   2 testcase1            2            0          10
#3   3 testcase3            2            2          10
#4   4 testcase2            0            2          10
#5   5 testcase5            0            2          10
#6   6 testcase1            2            0          10
#7   7 testcase3            2            2          10
#8   8 testcase5            0            2          10
#9   9 testcase2            0            2          10
#10 10 testcase3            2            2          10

我们可以在
数据表中使用联接

library(data.table)
setDT(df2)[df1, c('total_passed', 'total_failed', 'total_items')
         := .(passed, failed, 10), on = .(testid = testcase)]
library(data.table)
setDT(df2)[df1, c('total_passed', 'total_failed', 'total_items')
         := .(passed, failed, 10), on = .(testid = testcase)]