R 将斜杠转换为除法
我有一个字符类型的列,看起来像(1/1),(2/3),(4/5)等等 我想把它转换成向量,比如1,0.66,0.80等等 有没有一个简单的方法可以做到这一点 我能想到的唯一办法就是 伪码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] 编辑: 我的数据如下
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