小编Jac*_*ack的帖子

当我在R中申请时丢失课程信息

当我使用apply将一行数据帧传递给一个函数时,我丢失了该行元素的类信息.他们都变成了"性格".以下是一个简单的例子.我想给3个年龄段的人增加几年的时间.当我尝试添加2一个数字值时,R表示"对二元运算符的非数字参数".我该如何避免这种情况?

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)
Run Code Online (Sandbox Code Playgroud)

输出如下:

_age_ 
 "20" 
_age_ 
 "20" 
[1] FALSE
[1] "character"
Error in er[2] + 2 : non-numeric argument to binary operator
Run Code Online (Sandbox Code Playgroud)

r class apply

2
推荐指数
1
解决办法
1642
查看次数

标签 统计

apply ×1

class ×1

r ×1