Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将斜杠转换为除法_R_Rstudio - Fatal编程技术网

R 将斜杠转换为除法

R 将斜杠转换为除法,r,rstudio,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] 编辑: 我的数据如下

我有一个字符类型的列,看起来像(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"
试一试


假设这是你的数据

x <- c("1/1", "1/1", "3/3", "1/1", "1/1", "4/4", "1/1", "2/2", "4/5", "4/5")
或者按照@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


你能给我们展示一下你的数据吗?你真的在每个条目中都有括号吗?试试
eval(parse(text='2/3'))
或者对于向量,
sapply(gsub('[()]','',v1),函数(x)eval(parse(text=x))
@akrun我感觉到有人会建议,尽管它没有向量化,你需要类似
sapply(c)('1/1”,“2/3”,“4/5”),函数(x)eval(parse)(parse)(text=x))
可能很快就会有人添加一条评论,这条评论就会被抛出,等等。@davidernburg,请参见上面的编辑。@davidernburg是的,你是对的,使用
eval(parse
可能不是最佳选择,或者你可以使用
scan
矩阵(scan(text=x,what=numeric(),sep=“/”,quiet=TRUE),ncol=2,byrow=TRUE)
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
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
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