【问题标题】:Assign value based on row remainder根据行余数赋值
【发布时间】:2014-08-27 22:21:19
【问题描述】:

我想执行以下操作。我正在计算数据集中总行数除以 20 的余数,并基于余数 (0,1,2,...19) 我将 x1、x2、x3 等的值分配给名为的变量blf。例如,如果第 n 行 & 20 的余数为 0,则 blf = 0.8,如果第 n 行 & 20 的余数为 1,则 blf=0.7,如果第 n 行和 20 的余数为 2 或 3,则 blf =0.6 以此类推。当我在 R 中执行此操作时 (我的代码在下面,可以在此处找到示例数据集(Rdata 和 csv):http://goo.gl/qgbeIJ 我收到以下错误:

ifelse(sampledat[1:nrow(sampledat)%%20 == 0], 0.8, blf) 中的错误: (列表)对象不能被强制输入“逻辑”

sampledat$blf <- 0.1   
sampledat$blf <- with(sampledat, ifelse(sampledat[1:nrow(sampledat)%%20==0],0.8,blf ))
sampledat$blf <- with(sampledat, ifelse(sampledat[1:nrow(sampledat)%%20==1],0.7,blf ))
sampledat$blf <- with(sampledat, ifelse(sampledat[1:nrow(sampledat)%%20==2] | sampledat[1:nrow(sampledat)%%20==3] ,0.6,blf ))

一种可能的解决方案是将余数存储为一个名为 remain 的单独变量,然后根据向量值执行 ifelse 操作,但我想知道是否有办法一次性完成步。

sampledat$remain <- (1:nrow(sampledat))%%20
sampledat$blf <- 0.1   
sampledat$blf <- with(sampledat, ifelse(remain==0,0.8,blf ))
sampledat$blf <- with(sampledat, ifelse(remain==1,0.7,blf ))
sampledat$blf <- with(sampledat, ifelse(remain==2 | remain==3 ,0.6,blf ))

我们将不胜感激。

TIA, 克里希南

【问题讨论】:

  • 至少,如果remain 永远不会超过 3,则嵌套您的if-else 并将所有非 0 或 1 的情况分配给最终值。我也不认为你需要with - 就像sampledat$blf &lt;- 0.6 + 0.1*(sampledat$remain ==1) + 0.2*(sampledat$remain==0)
  • 余数大于3怎么办?
  • 相同的过程继续,根据余数分配给 blf 的不同值,直到 19 并且它对数据表中的所有记录重复自身。为简洁起见,没有包括一路余数 = 19。

标签: r


【解决方案1】:

你没有说余数为 3 之后会发生什么,所以我使用了 0.0。我通过两步(有点)易于理解的过程做到了这一点:

answers=c(0.8,0.7,0.6,0.6,0.0,
      0.0,0.0,0.0,0.0,0.0,
      0.0,0.0,0.0,0.0,0.0,
      0.0,0.0,0.0,0.0,0.0)

sampledata$blf<-answers[(as.numeric(rownames(sampledata))%%20)+1]

您可以根据需要修改 answers 数组。

【讨论】:

    猜你喜欢
    • 2014-05-19
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 2012-05-09
    • 2011-12-08
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多