运算符对函数内的原子向量无效

时间:2018-06-15 22:07:48

标签: r

我正在函数中使用下面的代码运行一个函数。

我是否应该将某些内容声明为数据框而不是我?

当它运行时我得到

  

“错误:$运算符对原子矢量无效”

如果我在创建z2$a数据框时将z2[,1]重新定义为ma2

  

z2 [,1]出错:维数不正确

 #---identifieds the loaction of the business address header and mailing address header
    ba <- grep("BUSINESS ADDRESS:",z$a)
    ma <- grep("MAIL ADDRESS:", z$a)

#-- create the business address dataframe from the main dataframe "z"
#--- if no "business address" header is found then set z2 dataframe to NA
#--- if yes on "business address" header set the z2 fram to the header  location and all
#--- rows below
  if(length(ba) > 0) {
    z2 <- z[ba:nrow(z),,drop = FALSE]
  } else {
    z2 <- NA
  }

#--- trim the business address df z2 if the mailing address is in the dataframe.
#--- if mailing address header "MAIL ADDRESS:" is found then the if statement
#--- will chop off mailing address and everything below it.
#--- if mailing address header is not found the z2 dataframe will remain as is

  ma2 <- grep("MAIL ADDRESS:",z2$a)

  if(length(ma2) > 0) {
    z2 <- z2[1:((ma2)-1),,drop = FALSE]
  } else {
    z2
  }

1 个答案:

答案 0 :(得分:1)

z2未被创建为数据框。 添加as.data.frame()会照顾好一切。