【问题标题】:Writing a thresholding function in R在 R 中编写阈值函数
【发布时间】:2021-03-11 01:17:11
【问题描述】:

我正在尝试创建一个函数,以便数据帧 df 中的每个值 x 如果高于 y 则替换为 1,否则替换为 0。

我试过了

> head(calcium)
        Cell 1    Cell 2    Cell 3    Cell 4    Cell 5    Cell 6    Cell 7    Cell 8    Cell 9   Cell 10   Cell 11
[1,] 0.6146776 0.1818022 0.2256154 0.6515446 0.6700386 0.6743005 1.0000000 0.3409436 0.4866678 0.5086616 0.5348238
[2,] 0.5285786 0.2274010 0.3376090 0.3034726 0.6279132 0.3015857 0.7044972 0.2319099 0.3035952 0.3714068 0.4642644
[3,] 0.3856135 0.2677357 0.2281765 0.3974314 0.2387615 0.2813382 0.5393310 0.1903822 0.2664197 0.4568273 0.4831306
[4,] 0.5510923 0.1949103 0.2009160 0.5039776 0.6978353 0.4433197 0.5311569 0.3177127 0.3471870 0.3847868 0.7146810
[5,] 0.4901831 0.2812967 0.2128641 0.5530176 0.4976631 0.2433328 0.5071555 0.2933614 0.3210706 0.5368088 0.4837594
[6,] 0.5935311 0.3517518 0.2255503 0.4359288 0.4147038 0.3238977 0.4404824 0.2185742 0.3462842 0.1811753 0.4795145

threshold <- function(x, y) if (x < y) {
  x <- 0 
  } else {
    x <- 1
}

使用它,返回一个警告:

> calcium.threshold
[1] 0.3335321

> threshold(calcium, calcium.threshold)
Warning message:
In if (x < y) { :
  the condition has length > 1 and only the first element will be used

我不知道为什么?

干杯。

编辑:道歉。我添加了我的数据框以供参考。

【问题讨论】:

  • 你的calcium 是什么?它是data.frame 还是向量?如果是dataframe,它的结构是什么?
  • 请提供一个完整的例子。没有人,但你可以运行它,因为你没有显示输入。请阅读r标签页顶部的发布说明。

标签: r function if-statement threshold


【解决方案1】:

这是一个使用 mtcars 和 cyl 列的示例:

cars <- mtcars
cars$cyl <- ifelse(cars$cyl > 4, 1, 0)
> head(cars, 6)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   1  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   1  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   0  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   1  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   1  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   1  225 105 2.76 3.460 20.22  1  0    3    1

所以对于你的情况:

df$x <- ifelse(df$x > y, 1, 0)

【讨论】:

    【解决方案2】:

    我们可以通过强制转换为整数来创建二进制

    cars <- mtcars
    cars$cyl <- as.integer(car$cyl > 4)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多