1
votes

I have a data frame which is retrieved from a csv file. I need to get the column types of some columns and apply these types to another data.frame's corresponding columns.

For example, after certain steps, the data.frame from the csv is called Table1.

header <- names(Table1)
"Acct" "Tran"
class(Table1$Acct)
"character"
class(Table1$Tran)
"character"

Then I need to convert Table2's corresponding "Acct" and "Tran" columns to character.

I tried

class(Table1[header])
[1] "data.frame"
class(Table1$header)
[1] "NULL"

How do I apply the column types of Table1 to Table2? Do I have to use for loop to do the transfer?

Thanks

****UPDATES**** Since the data types of Table1 are not complex, I created a function to manually convert column types. as.numeric(as.character(After)) is important. if After is a factor, as.numeric(After) will change the values.

Typeconvertion<- function(Before, After){

classtype<-class(Before)

if (classtype=="factor") {After<-as.character(After)}

else if(classtype=="integer"){After<- as.numeric(as.character(After))}

else if(classtype=="numeric"){After<- as.numeric(as.character(After))}

else if(classtype=="character"){After<- as.character(After)}

else {After<- After}

}

1
I don't see a reference to Table2 anywhere in your code. A reproducible example would be good.Rich Scriven
Table2 have the same columns with Table1, just with different column types. Now I need to convert table2 column types to table1 column types.kzhang12

1 Answers

0
votes

Consider a more flexible function.

    matchColClasses<- function(df1, df2){
    # Purpose:  protect joins from column type mismatches - a problem with multi-column empty df          
    # Input:    df1 - master for class assignments, df2 - for col reclass and return.
    # Output:   df2 with shared columns classed to match df1
    # Usage:    df2 <- matchColClasses(df1, df2)

      sharedColNames <- names(df1)[names(df1) %in% names(df2)]
      sharedColTypes <- sapply(df1[,sharedColNames], class)

      for (n in sharedColNames) {
        class(df2[, n]) <- sharedColTypes[n]
      }

      return(df2)
     }