如何分配申请家庭? [英] How to assign within apply family?

查看:132
本文介绍了如何分配申请家庭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的data.frame包含几个因素,我想重命名所有这些因素的因子级别。例如:

I have data.frame that contains several factors and i want to rename factor levels for all of these factors. E.g.:

mydf <- data.frame(col1 = as.factor(c("A","A",NA,NA)),col2 = as.factor(c("A",NA,NA,"A")))
mydf <- as.data.frame(lapply(mydf,addNA))

请注意,现实生活中的例子只有两列。因此,我想使用apply将其他级别的名称分配给所有这些列,就像:

Note that the real life example has way more than just two columns. Hence I would like to use apply to assign other level names to all of these columns, just like in:

levels(mydf$col1) <- c("1","0") 

没有工作...

 apply(mydf,1,function(x) levels(x) <- c("1","0"))

我不是很惊讶它不工作,但我没有更好想法现在我应该使用吗?

I am not really surprised it doesn't work but I have no better ideas right now. Should I use with maybe?

编辑:我意识到我在这里做了一个错误,简化了事情。我使用 addNA 来解释这个事实,NAs不应该像NAs那样处理。所以我也想重新标记他们。
这不适用于Andrie的建议,并返回以下错误消息:

I realized I made a mistake here by oversimplifying things. I used addNA to account for the fact, that NAs should not handled as NAs anymore. Thus I also want to relabel them. This doesn't work with Andrie's suggestion and returns the following error message:

 labels = c("1",  : invalid labels; length 2 should be 1 or 1  

请注意,我更新了我的示例df。 / p>

Note that I updated my example df.

推荐答案

您可以使用 setattr() a href =http://cran.r-project.org/web/packages/bit/index.html =noreferrer> bit data.table 。这避免了复制整个数据集,并且因为你说你有很多列...

You can change levels by reference using setattr() from packages bit or data.table. This avoids copying the whole dataset, and since you said you have a lot of columns ...

require(bit)          # Either package
require(data.table)   #
setattr(mydf[[1]],"levels",c("1","0"))
setattr(mydf[[2]],"levels",c("1","0"))

完成一个简单的循环是非常快的,你有责任确保tha您可以用相同长度的向量替换水平矢量,否则该因子可能不再有效。而且,您必须用此方法替换整个级别的矢量。在 data.table 中有内部方式通过引用替换特定级别的名称,但可能不需要那么远。

That can be done in a simple for loop which is very fast. It is your responsibility to ensure that you replace the levels vector with a vector of the same length, otherwise the factor may no longer be valid. And, you have to replace the whole levels vector with this method. There is an internal way in data.table to replace particular level names by reference, but probably no need to go that far.

这篇关于如何分配申请家庭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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