【问题标题】:function assignment error in a vector(R language)向量中的函数分配错误(R语言)
【发布时间】:2020-10-11 06:08:22
【问题描述】:

我需要在 x 中找到数字 35 并为其分配一个函数。 然后调用函数。 代码:

x  <- 1:100
z  <- 0

z[x == 35]  <- function() { # error here 
    
    print("hello")

}

z  <- max(z, na.rm=TRUE) # remove all NA in vector

z() # run it

错误:

Error in z[x == 35] <- function() { :
   incompatible types (from closure to double) in subassignment type fix 

谢谢!!

【问题讨论】:

  • z 应该是什么?您首先为其分配 0,然后尝试获取其不存在的第 35 个元素并为其分配一个函数?

标签: r function dataframe vector


【解决方案1】:

你的意思是这样的吗?

z  <- function(x) {  
    print("hello")
    max(x, na.rm=TRUE) # remove all NA in vector
  }


for (x in 1:100){
  if (x == 35){
    z(x)
  }
}

【讨论】:

    【解决方案2】:

    这正是你想要这样做的原因,但是......

    x  <- 1:100
    z  <- list()
    
    z[[which(x == 35)]]  <- function() {
      print("hello")
    }
    
    z[[which(x == 35)]]() # run it
    [1] "hello"
    
    

    关键是使用列表,而不是向量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 2016-02-15
      • 2012-11-25
      • 2018-03-31
      • 1970-01-01
      相关资源
      最近更新 更多