Dplyr Mutate_each for paired sets of columns

后端 未结 2 822
陌清茗
陌清茗 2021-01-14 23:07

Is there a way to achieve the following transformation using dplyr::mutate_each?

data.frame(x1 = 1:5, x2 = 6:10, y1 = rnorm(5), y2 = rnorm(5)) %>%
  mutat         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-14 23:39

    This does not use mutate_each, nor is it very pretty, nor do I think it will be very fast, but:

    #create data set
    p<-data.frame(x1 = 1:5, x2 = 6:10,
              y1 = rnorm(5), y2 = rnorm(5),
              z1 = 11:15, z2 = rnorm(5),
              w1 = rchisq(5,2), w2 = rgamma(5, .2)) 
    
    #subset the columns by their column number and subtract them
    p[,ncol(p)+seq(1,ncol(p)/2, by = 1)]<-
    p[,seq(1,ncol(p),by = 2)]-p[,seq(2,ncol(p), by = 2)]
    

    The data.frame p should be updated with half as many columns as it originally had, the new columns containing the difference of each pair (1-2, 3-4, 5-6) of originals.

提交回复
热议问题