Operation with 2 columns dynamically

Asked

Viewed 34 times

2

Be the data frame

v1 v2 v3 v4 v5
a  x  2  1  4
b  y  4  3  5
c  z  6  5  6

Calculate, for example: P1=v3+v4 P2=v4+v5 is trivial, because I can do this for each one manually, so I would have:

v1 v2 v3 v4 v5 p1 p2
a  x  2  1  4  3  5
b  y  4  3  5  7  8
c  z  6  5  6  11 11

Now, imagine that this file has 1000 columns! How to do this dynamically, that is, generate P1, P2, P3, ..., P100 ?

  • Always starting at v3, in the third column?

1 answer

3


The following code does what the question asks.
Uses only R base and I believe it does not depend on the data frame to process.

First a data frame for testing.

set.seed(4961)    # Torna os resultados reprodutíveis

m <- 5
n <- 10
dados <- as.data.frame(matrix(sample(100, m*n, TRUE), m, n))
colnames(dados) <- paste0("v", seq_len(ncol(dados)))

Now a function is defined that sums the columns two to two starting in the argument column from.

soma2cols <- function(DF, from = 3, prefix = "p"){
  nc <- ncol(DF)
  stopifnot(nc >= from)
  cols <- seq_len(nc)[-seq_len(from)]
  res <- sapply(cols, function(i) DF[[i - 1]] + DF[[i]])
  colnames(res) <- paste0(prefix, seq_len(ncol(res)))
  res
}

soma2cols(dados)
#      p1  p2  p3  p4  p5  p6  p7
#[1,] 153 100 100 180 130  72  76
#[2,]  74  70  45  79 118 135  87
#[3,] 112 104  69 139 143 125 119
#[4,] 156 103  84 141  90 109 161
#[5,]  26 101 175 153 108  99  91

result <- cbind(dados, soma2cols(dados))

result
#  v1 v2 v3 v4 v5 v6 v7 v8 v9 v10  p1  p2  p3  p4  p5  p6  p7
#1 44  9 69 84 16 84 96 34 38  38 153 100 100 180 130  72  76
#2 68 61  5 69  1 44 35 83 52  35  74  70  45  79 118 135  87
#3  5 69 28 84 20 49 90 53 72  47 112 104  69 139 143 125 119
#4 95 84 74 82 21 63 78 12 97  64 156 103  84 141  90 109 161
#5 52 77  4 22 79 96 57 51 48  43  26 101 175 153 108  99  91
  • thanks for the speed! It worked :) You would know how to reproduce the same result with DPLYR?

  • @user2725174 I believe that it would not or at least take longer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.