Convert columns of arbitrary class to the class of matching columns in another data.table

前端 未结 3 1777
忘了有多久
忘了有多久 2021-01-04 02:26

Question:

I\'m working in R. I want the shared columns of 2 data.tables (shared meaning same column name) to have matching classes. I\'m struggling

3条回答
  •  暖寄归人
    2021-01-04 02:58

    Based on the discussion in this question, and comments in this answer, I'm thinking I may have had it right, and just landed on an odd exception.

    Note that the class doesn't change, but the technicality is that it doesn't matter (for my particular use-case that prompted the question). Below I show my "failed approach", but by following through to the merge, and the classes of the columns in the merged data.table, we can see why the approach works: integers will just get promoted.

    s2c <- function (x, type = "list") 
    {
        as.call(lapply(c(type, x), as.symbol))
    }
    
    # In this case, I can assume all columns of A can be found in B
    # I am also able to assume that the desired conversion is possible
    B.class <- sapply(B[,eval(s2c(names(A)))], class)
    for(col in names(A)){
        set(A, j=col, value=as(A[[col]], B.class[col]))
    }
    
    # Below here is new from what I tried in question
    AB <- data.table:::merge.data.table(A, B, all=T, by=c("stratum","year"))
    
    sapply(AB, class)
      stratum      year        bt        yr 
    "integer" "numeric" "numeric" "numeric" 
    

    Although the problem in the question isn't solved by this answer, I figured I'd post to point out that the failure to convert "integer" to "numeric" might not be a problem in many situations, so this is a straightforward, albeit circumstantial, solution.

提交回复
热议问题