Home > Back-end >  Substract two DataFrames by Indexes in R
Substract two DataFrames by Indexes in R

Time:11-03

I would like to subtract two data frames by row indexes and keep rows in df1 if they are not in df2.

# TEST
df1 <- data.frame(V1=c(0,1,3,5,1,6), V2=6:11, V3=6:11); df1
df2 <- data.frame(V1=1:5, V2=c(0,1,3,5,1), v3=rep(0, 5)); df2

# DESIRED
df <- data.frame(V1=c(-1,-1,0,1,-4, 6), V2=c(6,6,5,4,9, 11), V3=c(6,7,8,9,10, 11)); df

CodePudding user response:

We could use the number of rows in df2 to index df1 and the rbind the remaining rows from df1 after the subtraction. This works as long as both data.frames have the same number of columns and df1 has at least as many rows as df2.

rbind(df1[1:nrow(df2), ] - df2, df1[(nrow(df2)   1):nrow(df1), ])

Returns:

  V1 V2 V3
1 -1  6  6
2 -1  6  7
3  0  5  8
4  1  4  9
5 -4  9 10
6  6 11 11

CodePudding user response:

You could calculate with the intersect of rownames, as far as I understand you want to change df1, so there's actually no need to rbind anything. Otherways just copy df1 before the operation.

ix <- intersect(rownames(df1), rownames(df2))
df1[ix, ] <- df1[ix, ] - df2[ix, ]
df1
#   V1 V2 V3
# 1 -1  6  6
# 2 -1  6  7
# 3  0  5  8
# 4  1  4  9
# 5 -4  9 10
# 6  6 11 11
  •  Tags:  
  • r
  • Related