How to convert multiple columns in R

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}

}


考虑一个更灵活的功能。

    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)
     }
链接地址: http://www.djcxy.com/p/70900.html

上一篇: 安全版本的子集

下一篇: 如何转换R中的多个列