Losing Class information when I use apply in R

前端 未结 1 1809
天涯浪人
天涯浪人 2021-02-11 03:06

When I pass a row of a data frame to a function using apply, I lose the class information of the elements of that row. They all turn into \'character\'. The following is a sim

相关标签:
1条回答
  • 2021-02-11 03:33

    apply only really works on matrices (which have the same type for all elements). When you run it on a data.frame, it simply calls as.matrix first.

    The easiest way around this is to work on the numeric columns only:

    # skips the first column
    a <- apply(df[, -1, drop=FALSE],1, dfunc)
    
    # Or in two steps:
    m <- as.matrix(df[, -1, drop=FALSE])
    a <- apply(m,1, dfunc)
    

    The drop=FALSE is needed to avoid getting a single column vector. -1 means all-but-the first column, you could instead explicitly specify the columns you want, for example df[, c('foo', 'bar')]

    UPDATE

    If you want your function to access one full data.frame row at a time, there are (at least) two options:

    # "loop" over the index and extract a row at a time
    sapply(seq_len(nrow(df)), function(i) dfunc(df[i,]))
    
    # Use split to produce a list where each element is a row
    sapply(split(df, seq_len(nrow(df))), dfunc)
    

    The first option is probably better for large data frames since it doesn't have to create a huge list structure upfront.

    0 讨论(0)
提交回复
热议问题