【问题标题】:Is there a construct similar to ifelse() which returns all the elements and not only the first one? [duplicate]是否有类似于 ifelse() 的构造,它返回所有元素而不仅仅是第一个元素? [复制]
【发布时间】:2016-07-31 20:32:51
【问题描述】:

在下面的例子中,i.want.them.all如何得到从5到14的所有10个数字?

control.me <- 0 # or 1
a.lot.of.elements <- c(5:14)
i.want.them.all <- ifelse(control.me == 1, a.lot.of.elements, a.lot.of.elements - 10)
print(i.want.them.all)
[1] 5

有这样的构造吗? :

a.lot.of.elements <- c(5:14)
i.want.them.now <- magic.construct(control.me == 1, a.lot.of.elements, a.lot.of.elements - 10)
print(i.want.them.now)
[1]  5  6  7  8  9 10 11 12 13 14

如果没有,我怎么能完成我想做的事?

【问题讨论】:

  • 如果您的条件导致length == 1“逻辑”,您可以使用简单的if(test) yes else no?ifelse 声明“测试”决定了输出的大多数属性(包括 length
  • 你应该阅读help(ifelse)

标签: r if-statement


【解决方案1】:

也许只是测试seq_along,因为任何正整数都将始终评估为 TRUE:

> i.want.them.now <- ifelse(seq_along(a.lot.of.elements), a.lot.of.elements, character())
> i.want.them.now 
 [1]  5  6  7  8  9 10 11 12 13 14

【讨论】:

  • 抱歉,我更新了我的问题。应该有一个控制结构作为 ifelse() 的第一个参数
  • ifelse 是一个函数,它返回的值与其第一个参数的长度相同……而if 是一个控制结构(尽管也是一个函数)。有一条评论(已删除)建议您可以使用 if(control.me==1){a.lot.of.elements} 。 (建议对ifelse 进行修改不会太远。)
猜你喜欢
  • 2015-08-08
  • 2021-09-30
  • 1970-01-01
  • 2012-10-08
  • 1970-01-01
  • 2015-03-21
  • 2012-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多