Q:

How to subtract one record from another data frame in R

I have two data frame. One data frame has only 1 record and 3 columns. Another data frame has 6 rows and 3 columns.
Now I want to subtract data frame 1 values from data frame 2 values.
Sample data:
df1 = structure(list(col1 = 2L, col2 = 3L, col3 = 4L), .Names = c("col1", 
"col2", "col3"), class = "data.frame", row.names = c(NA, -1L))

df2 = structure(list(col1 = c(1L, 2L, 4L, 5L, 6L, 3L), col2 = c(1L, 
2L, 4L, 3L, 5L, 7L), col3 = c(6L, 4L, 3L, 6L, 4L, 6L)), .Names = c("col1", "col2", "col3"), class = "data.frame", row.names = c(NA, -6L))

Final output should be like,
output = structure(list(col1 = c(-1L, 0L, 2L, 3L, 4L, 1L), col2 = c(-2L, 
-1L, 1L, 0L, 2L, 4L), col3 = c(2L, 0L, -1L, 2L, 0L, 2L)), .Names =      c("col1","col2", "col3"), class = "data.frame", row.names = c(NA, -6L))

A:

Try this..
# Creating Datasets
df1 = structure(list(col1 = 2L, col2 = 3L, col3 = 4L), .Names = c("col1", "col2", "col3"), class = "data.frame", row.names = c(NA, -1L))
df2 = structure(list(col1 = c(1L, 2L, 4L, 5L, 6L, 3L), col2 = c(1L,2L, 4L, 3L, 5L, 7L), col3 = c(6L, 4L, 3L, 6L, 4L, 6L)), .Names = c("col1", "col2", "col3"), class = "data.frame", row.names = c(NA, -6L))

# Output
data.frame(sapply(names(df1), function(i){df2[[i]] - df1[[i]]}))
#    col1 col2 col3
# 1   -1   -2    2
# 2    0   -1    0
# 3    2    1   -1
# 4    3    0    2
# 5    4    2    0
# 6    1    4    2

A:

If you do df2 - df1 directly you get
df2 - df1

Error in Ops.data.frame(df2, df1) : 
    ‘-’ only defined for equally-sized data frames

So let us make df1 the same size as df2 by repeating rows and then subtract
df2 - df1[rep(seq_len(nrow(df1)), nrow(df2)), ]

#  col1 col2 col3
#1   -1   -2    2
#2    0   -1    0
#3    2    1   -1
#4    3    0    2
#5    4    2    0
#6    1    4    2

Or another option is using mapply without replicating rows
mapply("-", df2, df1)

This would return a matrix, if you want a dataframe back
data.frame(mapply("-", df2, df1))

#  col1 col2 col3
#1   -1   -2    2
#2    0   -1    0
#3    2    1   -1
#4    3    0    2
#5    4    2    0
#6    1    4    2

