使用用户定义函数在 R 中应用() [英] apply() in R with user-defined function
问题描述
我有一个带有投票和政党标签的数据框
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
提取后不再有列名(但它们确实有 <代码>名称代码>):
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 中应用()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!