【问题标题】:How do i change a String value to an integer value in R-studio如何在 R-studio 中将字符串值更改为整数值
【发布时间】:2020-03-23 06:29:13
【问题描述】:

所以我有这个包含几个字符串变量的 csv 数据,我想将其更改为整数,我该怎么做?数据 >200000 我想将其更改为 200000

【问题讨论】:

标签: r


【解决方案1】:

删除标点符号,然后转换为数字:

x = c(1, 2, ">200")
as.numeric(gsub("[[:punct:]]", "", x))
# [1] 1 2 200

或者,对于列中的数据:

data$x = as.numeric(gsub("[[:punct:]]", "", data$x))

【讨论】:

    【解决方案2】:

    由于我没有继续说下去,我将给出一个通用的解决方案。

    数据:

    col <- sample(1:100, 5, replace=FALSE)
    col <- c(col, ">200000")
    df <- as.data.frame(col, stringsAsFactors = FALSE)
    

    解决方案 1:

    df$col[df$col == ">200000"] <- "200000"
    df$col <- as.integer(df$col)
    

    解决方案 2:

    df$col <- replace(df$col, df$col == ">200000", "200000")
    df$col <- as.integer(df$col)
    

    【讨论】:

    • 我认为as.numeric 在第二个代码中没有意义。输出仍然是字符。我使用x &lt;- c("&gt;200", "100", "100") 进行测试。
    • 我现在明白了。
    猜你喜欢
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多