将列值复制到新列

时间:2018-12-19 11:06:19

标签: r

我有一个数据框BLUP,

Location  Value
  A          3
  B          5
  C          10

我希望输出看起来像

Location   Value1  Location2   Value2   Diff(Value2-Value1)
A             3        A          3          0
A             3        B          5          2
A             3        C          10         7
B             5        A          3         -2
B             5        B          5          0
B             5        C          10         5
C             10       A          3         -7
C             10       B          5         -5
C             10       C          10         0

我不确定如何在R中为更大的数据帧创建此输出表。任何建议将不胜感激,因为我是R的新手。

1 个答案:

答案 0 :(得分:0)

Is this what you need? If you already have the first columns except the last, simply do

mutate(Diff=Value2-Value1)

Otherwise add columns using mutate. You can look at ?cbind too

    #Location1 and Value1 should already be in your data. 


library(tidyverse)
        BLUP %>% 
          rename(Location2=Location1,Value2=Value1) %>% 

          mutate(Location1=rep("A",3),Value1=rep(3,3),Diff=Value2-Value1) %>% 
          select(contains("1"),everything())