Convert from billion to million and vice versa

后端 未结 6 553
旧巷少年郎
旧巷少年郎 2020-11-30 15:27

Suppose I have the following data frame named DF. I would like to convert all the values in the Revenue column to the same unit.

         


        
6条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 15:58

    To maybe simplify the parsing procedure compared to the previous solutions. I am using the awesome library stringr:

    library(stringr)
    
    dd$units <- word(dd$Revenue, 2, sep = " ")
    dd$amounts <- word(dd$Revenue, 1, sep = " ")
    
    
    # The following lines create an extra column in the dataframe,
    # You can overwrite the original column if you so wish.
    
    # Convert to billions
    dd$convert_to_bn <- paste(as.numeric(dd$amounts) * ifelse(dd$units == "bn", 1 , 0.001), "bn")
    
    # Convert to millions
    dd$convert_to_mn <- paste(as.numeric(dd$amounts) * ifelse(dd$units == "Mn", 1 , 1000), "Mn")
    

提交回复
热议问题