Losing Class information when I use apply in R

心不动则不痛 提交于 2020-01-12 06:03:33

问题


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 simple example. I want to add a couple of years to the 3 stooges ages. When I try to add 2 a value that had been numeric R says "non-numeric argument to binary operator." How do I avoid this?

age = c(20, 30, 50) 
who = c("Larry", "Curly", "Mo") 
df = data.frame(who, age) 
colnames(df) <- c( '_who_', '_age_')
dfunc <- function (er) {

   print(er['_age_'])
   print(er[2])
   print(is.numeric(er[2]))

  print(class(er[2]))
  return (er[2] + 2)
}
a <- apply(df,1, dfunc)

Output follows:

_age_ 
 "20" 
_age_ 
 "20" 
[1] FALSE
[1] "character"
Error in er[2] + 2 : non-numeric argument to binary operator

回答1:


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.



来源:https://stackoverflow.com/questions/10037745/losing-class-information-when-i-use-apply-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!