【问题标题】:R: "$ operator is invalid for atomic vectors"R:“$ 运算符对原子向量无效”
【发布时间】:2019-11-04 13:41:47
【问题描述】:

我想做一个函数返回数据帧的特定列,因为我有几个数据帧,它们的名称只有一位。例如,我有:

mtcars1 <- data.frame(name1 = mtcars[5, 1], name2 = c(1, 8, 2, 9, 9))
mtcars2 <- data.frame(name1 = mtcars[5, 1], name2 = c(1, 8, 3, 9, 9))

foo <- function(i){
  x <- paste0("mtcars", i)$name2
  return(x)
}

foo(1) 应该返回 1 8 2 9 9foo2 应该返回 1 8 3 9 9

问题是我有错误:

paste0("mtcars", i)$name2 中的错误: $ 运算符对原子向量无效

这当然是一个简单的问题,但我该怎么做呢?

【问题讨论】:

    标签: r


    【解决方案1】:

    问题是paste0("mtcars", i)$name2 返回一个字符向量,它不能是$ 的子集。

    你可以使用get做你想做的事:

    > mtcars1 <- data.frame(name1 = mtcars[5, 1], name2 = c(1, 8, 2, 9, 9))
    > mtcars2 <- data.frame(name1 = mtcars[5, 1], name2 = c(1, 8, 3, 9, 9))
    > 
    > foo <- function(i){
    +   x <- get(paste0("mtcars", i))$name2
    +   return(x)
    + }
    > foo(1)
    [1] 1 8 2 9 9
    > foo(2)
    [1] 1 8 3 9 9
    

    【讨论】:

    • 我确信解决方案会很简单,谢谢 :)(我必须等待几分钟才能验证)
    【解决方案2】:

    你也可以使用eval():

    mtcars1 <- data.frame(name1 = mtcars[5, 1], name2 = c(1, 8, 2, 9, 9))
    mtcars2 <- data.frame(name1 = mtcars[5, 1], name2 = c(1, 8, 3, 9, 9))
    
    foo <- function(i){
          x <- eval(expr = parse(text=paste0("mtcars", i,"$name2")))
          return(x)
    }
    
    #>foo(1)
    #[1] 1 8 2 9 9
    #>foo(2)
    #[1] 1 8 3 9 9
    

    【讨论】:

    • 谢谢,我更喜欢 Colin FAY 的回答,但这也很有用
    猜你喜欢
    • 2021-08-20
    • 2014-05-15
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多