8

Hello I´am trying to subtract the column B from column A in a dat matrix to create a C column (A - B):

My input:

A  B
1  2
2  2
3  2
4  2

My expected output:

A  B  C
1  2 -1
2  2  0
3  2  1
4  2  2

I have tried: dat$C <- (dat$A - dat$B), but I get a: ## $ operator is invalid for atomic vectorserror

Cheers.

Bryan Hanson
  • 6,055
  • 4
  • 41
  • 78
user3091668
  • 2,230
  • 6
  • 25
  • 42
  • 4
    If you really mean a matrix you'll need `input[,"B"] - input[,"A"]` or possibly use direct indexing: `input[,2] - input[,1]` if A and B are the first two columns. The syntax you are using is for `data frames`. You can do `str(input)` to see what it is if you are not certain. – Bryan Hanson May 27 '14 at 11:21
  • @BryanHanson I apologize for supplying the answer when you placed this comment, I just didn't see it. – ccapizzano May 27 '14 at 11:32
  • No worries. Looks like they have their answer. – Bryan Hanson May 27 '14 at 11:35

3 Answers3

23

As @Bryan Hanson was saying in the above comment, your syntax and data organization relates more to a data frame. I would treat your data as a data frame and simply use the syntax you provided earlier:

> data <- data.frame(A = c(1,2,3,4), B = c(2,2,2,2))
> data$C <- (data$A - data$B)
> data
  A B  C
1 1 2 -1
2 2 2  0
3 3 2  1
4 4 2  2
ccapizzano
  • 1,556
  • 13
  • 20
  • 1
    With the data transformed to dataframe I am getting this error: `## - makes no sense to factors` Some idea of the problem source? – user3091668 May 27 '14 at 11:58
  • 1
    You should post `dput(head(str(your_data)))` so we can see what you are working with, otherwise we have to guess which is not a good use of time. Add that to your original post. – Bryan Hanson May 27 '14 at 12:09
4

Yes right, If you really mean a matrix, you can see this example

> x <- matrix(data=1:3,nrow=4,ncol=3)
> x
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    3    1
[3,]    3    1    2
[4,]    1    2    3
> x[,3] = x[,1]-x[,2]
> x
     [,1] [,2] [,3]
[1,]    1    2   -1
[2,]    2    3   -1
[3,]    3    1    2
[4,]    1    2   -1
> 
rischan
  • 1,553
  • 13
  • 19
0

However, one should absolutely point out here that matrix operations in R don't abide by the usual linear algebra closure.

> x[,3]-x[,1]
[1]  2 -1 -1  2
> is.matrix(x[,3]-x[,1])
[1] FALSE

Further, one more directly anticipates a column vector which can be obtained by applying the matrix transpose TWICE (which is weird in itself) with the first one casting the output as a matrix.

> t(t(x[,3]-x[,1]))
     [,1]
[1,]    2
[2,]   -1
[3,]   -1
[4,]    2

Or one can use the drop=FALSE option:

>x[,3,drop=FALSE] - x[,1,drop=FALSE]
     [,1]
[1,]    2
[2,]   -1
[3,]   -1
[4,]    2

Behavior of 2D slices From 3D array are fine though.