1

我真的很喜欢在 R 中使用帧语法。但是,如果我尝试使用 apply 来执行此操作,它会给我一个错误,即输入是一个向量,而不是一个帧(这是正确的)。是否有与 mapply 类似的功能可以让我继续使用框架语法?

df = data.frame(x = 1:5, y = 1:5)

# This works, but is hard to read because you have to remember what's
# in column 1 
apply(df, 1, function(row) row[1])

# I'd rather do this, but it gives me an error
apply(df, 1, function(row) row$x)
4

1 回答 1

2

Youcab't$在原子向量上使用,但我想你想用它来提高可读性。但是你可以使用[subsetter。

这里举个例子。下次请提供可重现的示例。没有数据,R 中的问题特别没有意义。

set.seed(1234)
gidd <- data.frame(region=sample(letters[1:6],100,rep=T),
                   wbregion=sample(letters[1:6],100,rep=T),
                   foodshare=rnorm(100,0,1),
                   consincPPP05 = runif(100,0,5),
                   stringsAsFactors=F)

  apply(gidd, ## I am applying it in all the grid here!
          1, 
        function(row) {
        similarRows = gidd[gidd$wbregion == row['region'] &
                         gidd$consincPPP05 > .8 * as.numeric(row['consincPPP05']),
                       ]
    return(mean(similarRows$foodshare))
  })

请注意,使用 apply 我需要转换为数字。

您还可以使用plyrordata.table来获得干净的语法,例如:

  apply(df,1,function(row)row[1]*2)

相当于

  ddply(df, 1, summarise, z = x*2)
于 2013-02-09T15:01:42.367 回答