Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

r - Convert from billion to million and vice versa

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.

Brands   Revenue
A        50.1 bn
B        41.2 bn
C        32.5 Mn
D        15.1 bn

Please note that bn and Mn are part of the vectors.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One idea,

new <- ifelse(gsub('.*\s+', '', DF$Revenue) == 'bn',
              as.numeric(gsub('[A-Za-z]', '', DF$Revenue))*1000, DF$Revenue)

new[!grepl('Mn', new)] <- paste(new[!grepl('Mn', new)], 'Mn', sep = ' ')
DF$Revenue <- new

DF
#  Brands  Revenue
#1      A 50100 Mn
#2      B 41200 Mn
#3      C  32.5 Mn
#4      D 15100 Mn

To do the opposite then,

new <- ifelse(gsub('.*\s+', '', DF$Revenue) == 'Mn',
               as.numeric(gsub('[A-Za-z]', '', DF$Revenue))/1000, DF$Revenue)

 new[!grepl('bn', new)] <- paste(new[!grepl('bn', new)], 'bn', sep = ' ')
 DF$Revenue <- new
 DF
#  Brands   Revenue
#1      A   50.1 bn
#2      B   41.2 bn
#3      C 0.0325 bn
#4      D   15.1 bn

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...