Skip to content

how to add a derived column to a data frame?

3 messages · r-help, Petr Savicky

#
On Sun, Jan 16, 2011 at 03:01:49PM +0800, r-help wrote:
For a general matrix "a", this can be done, for example

  x <- rowSums(a %% 13 == 0)
  b <- cbind(a, x)

If the residues in the columns are periodic, like in the 
example above, then also the vector x is periodic. If this
really occurs in the application, generating the new column
using this fact may also be useful. The "length.out" argument
of rep() can be used.

  y <- rep(rowSums(a[1:13, ] %% 13 == 0), length=1000)
  identical(x, y) # [1] TRUE

Petr Savicky.
#
On Sun, Jan 16, 2011 at 03:01:49PM +0800, r-help wrote:
I am sorry for an error in the previous solution for a general
matrix. It should be, for example

  x <- as.numeric(rowSums(a %% 13 == 0) != 0)
  b <- cbind(a, x)

or

  x <- (rowSums(a %% 13 == 0) != 0) + 0

Petr Savicky.