【问题标题】:How to convert from string to numeric value in R如何在R中从字符串转换为数值
【发布时间】:2013-11-13 21:59:42
【问题描述】:

我希望在 R 中绘制一组人的身高

B/c 5-11 这样的高度以字符串形式出现,我想知道是否有任何关于如何转换为数字以便绘制图形的提示。

【问题讨论】:

  • 'require(stringr)' 'Split
  • @HuubHoofs 如果您在函数中添加 as.numeric 和 /12,您的解决方案似乎有效: sapply(Split, function(x) as.numeric(x[1]) + (as.numeric (x[2]) / 12))。随意发布它作为答案。

标签: string r graph ggplot2 numeric


【解决方案1】:

它也适用于基本 R 函数:

sapply(strsplit(x, "-"), function(x) {x <- as.numeric(x); x[1] + x[2] / 12})

【讨论】:

    【解决方案2】:

    我假设您的数据是一个因素。如果这是正确的,您可以将所有级别编辑为数值,然后将因子转换为数值向量。

    levels(data$heights)  #Levels of the factor
    levels(data$heights)<-c(5*12+10,5*12+11,6*12,6*12+1) #Renaming factors in numerical make sure
    ##the numbers are in the same order as in your levels
    data$heights<-as.numeric(levels(data$heights))[data$heights]  #Changing factor GPA to numeric vector GPA
    data$heights
    

    请注意,如果您的 R 将您的数据作为一个因素读取,则此方法有效

    【讨论】:

      【解决方案3】:
      require(stringr) 
      Split <- str_split(x, "-")
      sapply(Split, function(x) x[1] + (x[2] / 11))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-11
        • 1970-01-01
        • 1970-01-01
        • 2022-08-12
        • 2023-03-24
        相关资源
        最近更新 更多