1

If you have two dataframes

df_A<-data.frame(AA =c(1,2,3), AB =c(1,4,9)
df_B<-data.frame(BA =c(4,5), BB = c(16,25))

if I do df_C<-df_A[1,] + df_B[1,] then I get AA = 5 and AB = 17

Basically it is adding the first row from the two data frames.

But if I do df_D<-df_A[3,]+df_B[3,] then I get AA = NA and BB = NA

The reason for the NA is because I don't have a third row in the df_B.

Is there any way where no values are present you just get the sum of whatever is available? In the above example, I would like to get df_D as AA = 3 and AB = 9.

demongolem
  • 9,474
  • 36
  • 90
  • 105
S_Dhungel
  • 73
  • 5

2 Answers2

1

If you are just interested in the sum, a quick fix would be to fill the empty rows with 0s:

update <- function(df, max_rows) rbind(df,rep(rep(0,ncol(df)), max_rows-nrow(df)))
max_rows <- max(nrow(df_A),nrow(df_B))
df_B <- update(df_B, max_rows)
df_A <- update(df_A, max_rows)
Lucy
  • 981
  • 7
  • 15
  • This is a good solution but it only works if you already have a row in the data frame but If you have an empty data frame then it will change the row names as explained here http://stackoverflow.com/questions/12614397/how-to-add-rows-to-empty-data-frames-with-header-in-r – S_Dhungel Mar 07 '17 at 20:31
0

How about this:

AddAndFix <- function (x,y)
{
  z <- x + y
  if (anyNA(z))
  {
    if (anyNA(x))
    {
      return(y)
    }
    return(x)
  }
  else return(z)
}

AddAndFix(df_A[1,],df_B[1,])
AddAndFix(df_B[3,],df_A[3,])
AddAndFix(df_A[3,],df_B[3,])
Greg Thatcher
  • 1,303
  • 20
  • 29