R中带有用户定义函数的apply() [英] apply() in R with user-defined function

查看:93
本文介绍了R中带有用户定义函数的apply()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其中包含了投票和聚会标签

I have a data frame with votes and party labels arranged thus

dat <- data.frame( v1=c(25, 0, 70), 
                   v2=c(75, 100, 20), 
                   v3=c(0, 0, 10), 
                   l1=c("pA", ".", "pB"), 
                   l2=c("pB", "pC", "pC"), 
                   l3=c(".", ".", "pD") )

,因此每一行都是分析的单位.只有投票方才需要考虑,此功能会提取赞成票或相应的标签

so that each row is a unit of analysis. Only vote-getting parties need consideration and this function extracts positive votes or the corresponding labels

getpos <- function(vector, vorl="v"){ # change to "l" to report labels
    vot <- vector[grep( "v", colnames(vector) )]; 
    lab <- vector[grep( "l", colnames(vector) )];
    if (vorl=="v") {vot[vot>0]} else {lab[vot>0]};
}
getpos(dat[1,])           # votes for obs 1
getpos(dat[1,], vorl="l") # labels for obs 1

我希望在数据帧dat的每一行中运行功能getpos,以便生成具有不同长度的表决/标签向量的列表.应用该函数不会返回我期望的结果:

I wish to run function getpos in every row of data frame dat in order to produce lists with vote/label vectors of different length. Applying the function does not return what I expect:

apply(X=dat, MARGIN=1, FUN=getpos, vorl="l")

有人可以发现问题吗?与此相关的是,能否更有效地实现这一目标?

Can anyone spot the problem? And related, can this be achieved more efficiently?

推荐答案

这里发生的是,数据帧中的行在被apply提取后不再具有列名(但它们确实具有names):

What's happening here is that the rows in the dataframe no longer have column names after being extracted by apply (but they do have names):

尝试:

getpos <- function(x, vorl="v"){ 
     vot <- x[grep( "v", names(x) )] ;  lab <- x[grep( "l", names(x) )];
     if (vorl=="v") {vot[vot>0]} else {lab[vot>0]};
 }

> apply(dat, MARGIN=1, FUN=function(x2) getpos(x2, vorl="l") )
#-------------
[[1]]
  l1 
"pA" 

[[2]]
  l2 
"pC" 

[[3]]
  l1   l3 
"pB" "pD" 

这篇关于R中带有用户定义函数的apply()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆