Why can't I add numbers to the data framework created with cbind?

I need advice on how to subtract values ​​from each other listed in two data frames. In the example below with two data frames A and B, I would like to subtract the values ​​of the 2nd column from each other, provided that the first column vectors coincide. For example, when the vector X1 is R1, then 5.1 - 5 and 4.8 - 5 ..

and <-data.frame (cbind (with ('R 1', 'R 1', 'R 2', 'R 4', 'R 4', 'R 4'), s (5.1,4.8,4.9, 5.0,5.0, 5,3)))

In <-data.frame (cbind (with ('R 1', 'R2', 'R 3', 'R 4'), s (5,4.9,5.2,5.1)))

+4
source share
3 answers

General R Recommendations: DO NOT USE cbind WHEN IT IS REQUIRED:

 A <- data.frame(X1=c('R1','R1','R2','R4','R4','R4'),X2=c(5.1,4.8,4.9,5.0,5.0,5.3)) B <- data.frame(X1=c('R1','R2','R3','R4'),X2=c(5,4.9,5.2,5.1)) 

(You did factors of these numbers, and you cannot apply arithmetic operators to factors.)

If there are unique matches, the merge function returns all possible pairs:

 merge(A,B, by=1) merge(A,B, by=1)[,2] - merge(A,B, by=1)[,3] #[1] 0.1 -0.2 0.0 -0.1 -0.1 0.2 
+3
source

Define your data so that the numeric columns are indeed numeric. (With spaces for readability!)

 A <- data.frame( X1 = c('R1', 'R1', 'R2', 'R4', 'R4', 'R4'), X2 = c(5.1, 4.8, 4.9, 5.0, 5.0, 5.3) ) B <- data.frame( X1 = c('R1', 'R2', 'R3', 'R4'), X2 = c(5, 4.9, 5.2, 5.1) ) 

Combine data frames, and then subtract the columns with the result.

 merged <- merge(A, B, "X1") with(merged, X2.x - X2.y) 
+2
source

Here is a solution with vector names.

 A <- data.frame( X1 = c('R1', 'R1', 'R2', 'R4', 'R4', 'R4'), X2 = c(5.1, 4.8, 4.9, 5.0, 5.0, 5.3), stringsAsFactors = FALSE ) L <- c(5, 4.9, 5.2, 5.1) names(L) <- c('R1', 'R2', 'R3', 'R4') A$X2-L[A$X1] 
0
source

All Articles