Is it possible to swap columns around in a data frame using R?

后端 未结 7 2011
野的像风
野的像风 2020-12-08 19:54

I have three variables in a data frame and would like to swap the 4 columns around from

\"dam\"   \"piglet\"   \"fdate\"   \"ssire\"

to

7条回答
  •  温柔的废话
    2020-12-08 20:40

    d <- data.frame(a=1:3, b=11:13, c=21:23)
    d
    #  a  b  c
    #1 1 11 21
    #2 2 12 22
    #3 3 13 23
    d2 <- d[,c("b", "c", "a")]
    d2
    #   b  c a
    #1 11 21 1
    #2 12 22 2
    #3 13 23 3
    

    or you can do same thing using index:

    d3 <- d[,c(2, 3, 1)]
    d3
    #   b  c a
    #1 11 21 1
    #2 12 22 2
    #3 13 23 3
    

提交回复
热议问题