如何使用 tapply 并保留值的顺序
希望这不是一个太愚蠢的问题,但作为一个 R 初学者,我对 tapply 有一个严重的问题。可以说
factors <- as.factor( c("a", "b", "c", "a", "b", "c", "a", "b", "c") )
values <- c( 1, 2, 3, 4, 5, NA, 7, NA, NA )
tapply(
values,
factors,
function(x){
if( sum(is.na(x)) == 1 ){
x[ is.na(x) ] <- 0
}
return(x)
}
)
结果是
$a
[1] 1 4 7
$b
[1] 2 5 0
$c
[1] 3 NA NA
但是,我需要的是返回一个保留值的原始顺序的向量,即:
c( 1,2,3,4,5,NA,7,0,NA )
提前非常感谢。
hopefully this is not a too dumb question, but still being an R beginner I have a serious problem with tapply. Lets say
factors <- as.factor( c("a", "b", "c", "a", "b", "c", "a", "b", "c") )
values <- c( 1, 2, 3, 4, 5, NA, 7, NA, NA )
tapply(
values,
factors,
function(x){
if( sum(is.na(x)) == 1 ){
x[ is.na(x) ] <- 0
}
return(x)
}
)
The result is
$a
[1] 1 4 7
$b
[1] 2 5 0
$c
[1] 3 NA NA
However, what I need is to get a vector back which preserves the original order of values, i.e.:
c( 1,2,3,4,5,NA,7,0,NA )
Many thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在这种情况下,您应该使用
ave
函数:In that case you should use the
ave
function:一个简单的
for
循环可以非常简单地完成此操作:A simple
for
loop does this very simply:一种选择是使用 split() 的替换方法:
An option is to use the replacement method for split():
如果其他人通过搜索如何禁用组的字母排序发现此问题,您可以执行以下操作:
In case others found this question by searching for how to disable alphabetic sorting for the groups, you can do this: