将带有点和逗号的字符串转换为数字

时间:2018-02-20 11:23:39

标签: r type-conversion numeric

有没有办法将字符串类型转换为数字类型? 例如:

> as.numeric("1.560")
[1] 1.56
> as.numeric("1.560")>2
[1] FALSE

我收到上述错误。 我需要显示数千个并用点分隔,同时(即1.560)显示小数并用逗号分隔。

    Just add margin-top : -10px in css for this css property letter-anim.letter-anim-dynamic p

 <h1 class="letter-anim h1-firstname">
      <span class="letter-anim-static">
        レ・ジェーン<br/>
      </span>
      <span class="letter-anim-dynamic">
        <p>Lejeune</p>
      </span>
    </h1>

    <br/>

    <h1 class="letter-anim h1-lastname">
      <span class="letter-anim-static">
        ジョゼーフ<br/>
      </span>
      <span class="letter-anim-dynamic">
        <p>Joseph</p>
      </span>
    </h1>


    h1{
        display:inline-block;
        font-family: sans-serif;
        font-size: 110px;
        letter-spacing: 3px;
        margin:0;
        line-height: 90px;
    }
    h1 p{margin:0;}

    /*************************************************/
    /************* LETTER ANIMATION HOVER ************/
    /* Thanks to https://codepen.io/nikolamitic/pen/vpNoNq */

    .letter-anim{
        position: relative;
        color: #fff;
        background-color: #222;
        overflow: hidden;
        cursor: pointer;
    }

    .letter-anim .letter-anim-dynamic,
    .letter-anim  .letter-anim-dynamic p {    
        display: flex;
        justify-content: left;
        align-items: center;
        position: absolute;
        top:0;
        left:0;
        right:0;
        bottom:0;
        z-index: 2;
        transition: all ease 0.7s;
      margin-top: -10px;
    }
    .letter-anim  .letter-anim-dynamic{
        background-color: #fff;
        color: #222;
        overflow: hidden;
    }
    .letter-anim.active .letter-anim-dynamic,
    .letter-anim:hover .letter-anim-dynamic {
        transform: translateX(100%);
    }
    .letter-anim.active  .letter-anim-dynamic p,
    .letter-anim:hover .letter-anim-dynamic p {
        transform: translateX(-100%);
    }
    .letter-anim-static{
        font-size: 76px;
    }

在上面的例子中,当我希望R将1.560转换为数字时,它将其转换为1.56,这不是千位,而是低于2,因此我的计算是错误的。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

您必须使用regexpr将字符串格式化为R的可理解格式,然后将其转换为数字

public int compareTo(Object o) {
    Film film = (Film)o;
    return this.title1.compareTo(film.title1);
}

对于数字格式,请参阅as.numeric(gsub(",", "\\.", gsub("\\.","", "1.560,65"))) [1] 1560.65

formatC

答案 1 :(得分:1)

可以使用gsub函数完成字符串模式匹配和替换。以下是您的案例示例:

str_numbers <- c("1.560,65", "134,2","123","0,32")
as.numeric(gsub(",", "\\.", gsub("\\.", "", str_numbers)))

第一个调用用空字符串替换.。第二个,.

> (tmp <- gsub("\\.", "", str_numbers))
[1] "1560,65" "134,2"   "123"     "0,32"   
> gsub(",", "\\.", tmp)
[1] "1560.65" "134.2"   "123"     "0.32"