0
votes

Firstly, I have two dataframe I combined dataframes having same columns but different suffixes using common column removing suffix of the columns. Now I have to calculate difference between each two columns with same column names in a dataframe in R

I tried getting the unique column column names and form that substracting the columns, but common Id column converting to NA.

ffsub[[k]][[i-1]] <- sapply(unique(names(temp)),
            function(x) apply(temp[grep(x, names(temp))], 1, function(y) { y[1] - y[2] }))                  

also tried;

ffsub[[k]][[i-1]] <- sapply(unique(names(temp)[2:21]), 
                     function(x) apply(temp[grep(x, names(temp)[2:21])], 1, 
                     function(y) if ( all(is.na(y)) ) {NA} else { y[1] - y[2] }))

Result should be the difference between cloumns having same col names in dataframe.

1
explanation is not clear , provide some sample of data framesShijith
why not do the subtraction before the combination?DarrenRhodes
I got the resultKavya Vallela

1 Answers

0
votes

I tried to get difference of columns having same column names in different lists .
Lists are f1, f2; fsub is the list that stores result of difference temp is the list which has merged columns from two lists.
ID is the common column from two lists.
temp <- merge(f1,f2, by = "ID")
fsub[[f1]][[f2]] <- sapply(unique(names(temp)), function(x) apply(temp[grep(x, names(temp))], 1, function(y) if ( all(is.na(y)) ) {NA} else { if(is.na(y[2])){y[1]} else {y[1] - y[2] }}))
unique(names(temp) -> getting unique column names from merged list
1 -> column 1 which id ID in both lists
if ( all(is.na(y)) ) {NA} -> if all columns in lists having null values replaces with NA
So by doing this I got the difference between columns.