将斜线转换为分割

时间:2015-05-31 17:27:18

标签: r rstudio

我有一个类型字符的列,看起来像(1/1),(2/3),(4/5)等。

我想将其转换为1,0.66,0.80等的矢量。

有一种简单的方法吗?

我能想到的唯一方法就是

伪代码

separate string delimited by slash, as part[1] and part[2]
part[1] = as.integer(part[1])
part[2] = as.integer(part[2])
score = part[1]/part[2] 

编辑: 我的数据如下所示

> df[1:10,"score"]
 [1] "1/1" "1/1" "3/3" "1/1" "1/1" "4/4" "1/1" "2/2" "4/5" "4/5"
> class(df$score)
[1] "character"

2 个答案:

答案 0 :(得分:2)

假设这是您的数据

x <- c("1/1", "1/1", "3/3", "1/1", "1/1", "4/4", "1/1", "2/2", "4/5", "4/5")

使用read.table

with(read.table(text = x, sep = "/"), V1 / V2)
## [1] 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.8 0.8

或者根据@akruns评论,使用scan

temp <- scan(text = x, what = numeric(), sep = "/", quiet = TRUE)
temp[c(TRUE, FALSE)]/temp[c(FALSE, TRUE)]
## [1] 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.8 0.8

或使用strsplit

temp <- as.numeric(unlist(strsplit(x, "/")))
temp[c(TRUE, FALSE)]/temp[c(FALSE, TRUE)]
## [1] 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.8 0.8   

或者

library(gsubfn)
as.numeric(gsubfn("([0-9]+)/([0-9]+)", ~ as.numeric(x)/as.numeric(y), x))
## [1] 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.8 0.8        

答案 1 :(得分:1)

尝试

 as.numeric(sub('\\/.*', '', v2))/as.numeric(sub('.*\\/', '', v2))