如何通过计算在数据框列上执行true或false语句?

时间:2018-06-07 20:56:10

标签: r if-statement dataframe statistics finance

我正在尝试在财务数据的数据框架中运行if{}else{}语句。我尝试了各种不同的路线,但似乎无法集中精力正确读取数据的东西。

我尝试过较小的样本;

                  O        H        L        C    StoHH    StoLL          K        kM Tr
2007-02-23 9.274052 9.293215 9.269759 9.283475 9.455829 9.229304 0.23913917 0.2587985  0
2007-02-26 9.300035 9.349619 9.266349 9.321300 9.455829 9.229304 0.40611853 0.2809329  0
2007-02-27 9.322654 9.579280 9.336498 9.565459 9.579280 9.229304 0.96050872 0.5352555  0
2007-02-28 9.581271 9.609756 9.510326 9.560271 9.609756 9.238159 0.86683154 0.7444863  0
2007-03-01 9.556549 9.686216 9.507037 9.561439 9.686216 9.238159 0.72151534 0.8496185  0
2007-03-02 9.550849 9.740609 9.545815 9.732355 9.740609 9.238159 0.98357249 0.8573065  0
2007-03-05 9.772542 9.850654 9.776493 9.798985 9.850654 9.238159 0.91564176 0.8735765  0
2007-03-06 9.785914 9.800714 9.659360 9.681929 9.850654 9.238159 0.72452836 0.8745809  0
2007-03-07 9.682955 9.753325 9.678526 9.799160 9.850654 9.238159 0.91592748 0.8520325  0
2007-03-08 9.798771 9.754936 9.649990 9.662383 9.850654 9.238159 0.69261627 0.7776907  0
2007-03-09 9.656704 9.694217 9.590265 9.617014 9.850654 9.238159 0.61854382 0.7423625  0
2007-03-12 9.605565 9.664844 9.582515 9.676105 9.850654 9.238159 0.71501971 0.6753933  0
2007-03-13 9.673779 9.873512 9.675159 9.885906 9.873512 9.266349 1.02041297 0.7846588  0
2007-03-14 9.893805 9.908378 9.809037 9.834033 9.908378 9.266349 0.88420305 0.8732119  0
2007-03-15 9.830605 9.822618 9.788816 9.833431 9.908378 9.336498 0.86894628 0.9245208  0
2007-03-16 9.823855 9.937603 9.832304 9.936606 9.937603 9.507037 0.99768444 0.9169446  0
2007-03-19 9.911422 9.894650 9.830386 9.886574 9.937603 9.507037 0.88148391 0.9160382  0
2007-03-20 9.871804 9.858855 9.780539 9.834216 9.937603 9.545815 0.73611494 0.8717611  0
2007-03-21 9.833709 9.825223 9.730592 9.732152 9.937603 9.582515 0.42140821 0.6796690  0
2007-03-22 9.731063 9.723312 9.577633 9.585578 9.937603 9.577633 0.02207128 0.3931981  0
2007-03-23 9.596751 9.600287 9.536365 9.579816 9.937603 9.536365 0.10829234 0.1839239  0

使用;

a.2 = a.1[40:60,]
   sapply(a.2$K, as.numeric)
   if (a.2$K >= 0.8) {
    a.2$Tr = (a.2$O - a.2$C)* s
    } else {
            a.2$Tr = 0}

但它似乎没有将K中的值注册为> = 0.8。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

我相信你的问题在于不存储数值。尝试:

a.2$K = as.numeric(a.2$K)

答案 1 :(得分:0)

您不需要在此使用sapply,您可以将其全部放入已经向量化的ifelse

a.2$Tr<-ifelse(as.numeric(a.2$K)>=0.8, (a.2$O-a.2$C)*s,  0)