[R] create function for compare two dataframe.

Hiroyuki Sato hiroysato at gmail.com
Mon Feb 29 09:43:48 CET 2016


Hello

I would like to create a funciton which is create new dataframe
for compare reslut of two dataframes.

  No.  COLUMN DF1  DF2
  "1"  "VAL1" "2"  "0" # <- compare ID1,VAL1
  "2"  "VAL2" "3"  "2" # <- comapre ID2,VAL2
  "3"  "VAL3" "4"  "2" # <- compare ID3,VAL3

s1 <- read.table("sample1.txt",header=T,sep=',')
s2 <- read.table("sample2.txt",header=T,sep=',')
comp_data(df1,df2)

sample1.txt
  ID,VAL1,VAL2,VAL3
  ID1,2,2,3
  ID2,0,3,3
  ID3,0,2,4

sample2.txt
  ID1,0,2,3
  ID2,0,2,3
  ID3,0,2,2

I created the functions, but I got the following error.
Could you tell me how to add new frame data?
Or alternative way?

  1: In `[<-.factor`(`*tmp*`, ri, value = "3") :
    invalid factor level, NA generated
  2: In `[<-.factor`(`*tmp*`, ri, value = "VAL3") :
    invalid factor level, NA generated
  3: In `[<-.factor`(`*tmp*`, ri, value = "4") :
    invalid factor level, NA generated



  comp_data <- function(df1,df2) {
    #
    # create null data.frame
    out <- data.frame(matrix(rep(NA,4),nrow=1))[numeric(0), ]
    colnames(out) <- c("ID","Site","df1","df2")

    # column names
    col_names <- colnames(df1)

    # col_size
    col_size <- ncol(df1)
    row_size <- nrow(df1)

    for( col in 2:col_size ){
      for( row in 1:row_size ){
        if( df1[row,col] != df2[row,col] ){
          out <-
rbind(out,c(df1[row,1],col_names[col],df1[row,col],df2[row,col]))
        }
      }
    }
    out
  }

Best regards.

	[[alternative HTML version deleted]]



More information about the R-help mailing list