【问题标题】:How to Remove part of a String and Convert a Number如何删除部分字符串并转换数字
【发布时间】:2018-12-12 12:41:30
【问题描述】:

我对 R 非常陌生,并且遇到了数据框的问题。

所以我有一个看起来像这样的数据框 dataf:

#         PlayerName           playerValue
#5     Tammy Abraham          10,00 Mill. €  
#6     Abdul Rahman Baba      8,00 Mill. €  
#7     Mario Pasalic          8,00 Mill. €  
#8     Lewis Baker            5,50 Mill. €  
#9     Ola Aina               4,00 Mill. €  
#10    Jamal Blackman         500 Th. €  

然后我用这条线:

dataf$playerValue <- gsub(",", ".", gsub("[[:space:]].*", "", dataf$PlayerValue))

这个的输出是:

#         PlayerName           playerValue        playerValue
#5     Tammy Abraham          10,00 Mill. €           10
#6     Abdul Rahman Baba      8,00 Mill. €            8
#7     Mario Pasalic          8,00 Mill. €            8
#8     Lewis Baker            5,50 Mill. €            5.5
#9     Ola Aina               4,00 Mill. €            4
#10    Jamal Blackman         500 Th. €               500

有没有办法让最终值从 500 变为 0.5?因为显然 500,000 小于 400 万,但这里的 int 500 将大于 4。

另外,我如何排除原始的 PlayerValue 列?当我运行我的代码时,它会打印出两次列,一次是最后的字符串和转换后的列。

感谢您的帮助。

【问题讨论】:

  • 就打印两次而言,请注意playerValuePlayerValue 不同。你有一个错字。至于你的其他问题,我没有看到任何使用ifelse() 的捷径来检查"Th" 的条件,但也许有人比我有更多的正则表达式专业知识。

标签: r


【解决方案1】:

这是一个想法,它从每个字符串中提取值,如果在字符串中找不到单词Mill,则除以 1000,即

假设数据框,

 playerName         playerValue
1  Tammy Abraham    10,00 Mill. €
2 Jamal Blackman    500 Th. €

那么,

v1 <- as.numeric(gsub('\\D+', '', gsub(',.*', '', df$playerValue)))
v1[!grepl('Mill', df$playerValue)] <- v1[!grepl('Mill', df$playerValue)] / 1000
v1
#[1] 10.0  0.5

Here is a very similar question虽然不完全一样

【讨论】:

    【解决方案2】:

    在提取数字时,您可以使用regex 来分隔百万/千。

    # dummy data
    dataf <- data.frame(playerValue = c("500 Th. € ","4,00 Mill. € "))
    # Extract with regex
    mils <- 10^3 * as.numeric(gsub("^(\\d+?)\\,(\\d+?)\\s.*|^(\\d+?)\\s.*", "\\1", 
                                   dataf$playerValue, perl = TRUE))
    thsd <- as.numeric(gsub("^(\\d+?)\\,(\\d+?)\\s.*|^(\\d+?)\\s.*", "\\2\\3", 
                       dataf$playerValue, perl = TRUE))
    # Final result
    rowSums(cbind(mils, thsd), na.rm = TRUE)
    # returns
    [1]  500 4000
    

    【讨论】:

    【解决方案3】:

    这是一个使用 strsplitifelse 的简单答案。

    # Dummy data
    df <- data.frame(playerValue = c("500 Th. € ","4,00 Mill. € "), stringsAsFactors = FALSE)
    
    # Splitting number and scale into two columns
    splits <- strsplit(df$playerValue, split = " ")
    splits <- do.call(rbind, splits)
    
    # Replacing commas
    splits[,1] <- gsub(",", ".", splits[,1])
    
    # Adding to dataframe
    df$value <- as.numeric(splits[,1])
    df$scale <- splits[,2]
    
    # Calculating new values
    df$new_value <- ifelse(df$scale == "Th.", df$value/1000, df$value)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-18
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      • 2017-07-02
      相关资源
      最近更新 更多