[R] how to add a derived column to a data frame?
    Petr Savicky 
    savicky at praha1.ff.cuni.cz
       
    Sun Jan 16 10:36:27 CET 2011
    
    
  
On Sun, Jan 16, 2011 at 03:01:49PM +0800, r-help wrote:
> I have a data frame with 10 columns: A:J and I want to have the output as a data frame with 11 columns, the value of 11th column is??
> 
> 
> for each row, if any column can be divided by 13, then the 11th column has a values of 1, otherwise, it has a value of 0. How to do that?
> 
> 
> input is
> 
> a=matrix(1:10000,1000,10)
> 
> dimnames(a)=list(NULL,LETTERS[1:10])
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.
    
    
More information about the R-help
mailing list