Subtracting two columns to give a new column in R

85,038

Solution 1

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

Solution 2

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
> 
Share:
85,038
user3091668
Author by

user3091668

Updated on July 09, 2022

Comments

  • user3091668
    user3091668 almost 2 years

    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.

  • user3091668
    user3091668 almost 10 years
    With the data transformed to dataframe I am getting this error: ## - makes no sense to factors Some idea of the problem source?
  • Bryan Hanson
    Bryan Hanson almost 10 years
    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.