Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - How to perform arithmetic on values and operators expressed as strings?

I have a character variable with ratios (proportions) expressed as strings:

x <- c("2/3", "5/6", "3/11").

I want to convert the character values in x into percentages. Thus, my desired output would be:

c(2/3, 5/6, 3/11) * 100
# [1] 66.66667 83.33333 27.27273 

When I try the as.numeric(x), a warning message is generated (NAs introduced by coercion) and all elements are converted into NA

What to do?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here are some alternatives:

1) read.table Read the text in as if it were a file and then divide:

with(read.table(text = x, sep = "/"), 100 * V1 / V2)
## [1] 66.66667 83.33333 27.27273

2) eval/parse eval/parse is generally frowned upon but here is how it would work:

100 * sapply(as.list(parse(text = x)), eval)
## [1] 66.66667 83.33333 27.27273

3) strsplit

sapply(strsplit(x, "/"), function(x) { x <- as.numeric(x); 100 * x[1] / x[2]})
## [1] 66.66667 83.33333 27.27273

4) gsubfn::strapply This picks out the two strings of digits using strapply and then converts each to numeric and divides:

library(gsubfn)

strapply(x, "(\d+)/(\d+)", ~ 100 * as.numeric(x) / as.numeric(y), simplify = TRUE)
## [1] 66.66667 83.33333 27.27273

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...