我想用乘法运算符将字符串转换为数字。在我的数据帧mydf
中,有一列ESPAC
,我的想法是转换第一行,例如:;2.70x2.20";使用CCD_ 3的操作。有简单的方法吗?我想要的最终输出是mydf2
:
ID<-1:9
ESPAC<-c("2.70x2.20","3.5X2","3.6X2","3.00x1.33","3.00x2.00","3.00x2.50","3.00x3.00","3.5x2.14","3.90x2.32")
mydf<-data.frame(ID,ESPAC)
mydf
# ID ESPAC
#1 1 2.70x2.20
#2 2 3.5X2
#3 3 3.6X2
#4 4 3.00x1.33
#5 5 3.00x2.00
#6 6 3.00x2.50
#7 7 3.00x3.00
#8 8 3.5x2.14
#9 9 3.90x2.32
mydf2
# ID ESPAC
#1 1 5.9
#2 2 7.0
# ...
#9 9 9.0
在用*
替换x
后,您还可以使用eval
、parse
、text
。
mydf$ESPAC <- sapply(gsub('x', '*', mydf$ESPAC, ignore.case = TRUE),
function(x) eval(parse(text = x)))
mydf
# ID ESPAC
#1 1 5.940
#2 2 7.000
#3 3 7.200
#4 4 3.990
#5 5 6.000
#6 6 7.500
#7 7 9.000
#8 8 7.490
#9 9 9.048
基R
mydf$res <- sapply(strsplit(mydf$ESPAC, "[Xx]"), function(z) prod(as.numeric(z)))
mydf
# ID ESPAC res
# 1 1 2.70x2.20 5.940
# 2 2 3.5X2 7.000
# 3 3 3.6X2 7.200
# 4 4 3.00x1.33 3.990
# 5 5 3.00x2.00 6.000
# 6 6 3.00x2.50 7.500
# 7 7 3.00x3.00 9.000
# 8 8 3.5x2.14 7.490
# 9 9 3.90x2.32 9.048
dplyr
library(dplyr)
mydf %>%
mutate(res = sapply(strsplit(ESPAC, "[Xx]"), function(z) prod(as.numeric(z))))
# ID ESPAC res
# 1 1 2.70x2.20 5.940
# 2 2 3.5X2 7.000
# 3 3 3.6X2 7.200
# 4 4 3.00x1.33 3.990
# 5 5 3.00x2.00 6.000
# 6 6 3.00x2.50 7.500
# 7 7 3.00x3.00 9.000
# 8 8 3.5x2.14 7.490
# 9 9 3.90x2.32 9.048
数据
mydf <- structure(list(ID = 1:9, ESPAC = c("2.70x2.20", "3.5X2", "3.6X2", "3.00x1.33", "3.00x2.00", "3.00x2.50", "3.00x3.00", "3.5x2.14", "3.90x2.32"), res = c(5.94, 7, 7.2, 3.99, 6, 7.5, 9, 7.49, 9.048)), row.names = c(NA, -9L), class = "data.frame")
我们可以在vectorized
方式中做到这一点
library(dplyr)
library(tidyr)
mydf %>%
separate(ESPAC, into = c('res', 'res2'), sep="[xX]",
convert = TRUE, remove = FALSE) %>%
mutate(res = res * res2, res2 = NULL)
ID ESPAC res
1 1 2.70x2.20 5.940
2 2 3.5X2 7.000
3 3 3.6X2 7.200
4 4 3.00x1.33 3.990
5 5 3.00x2.00 6.000
6 6 3.00x2.50 7.500
7 7 3.00x3.00 9.000
8 8 3.5x2.14 7.490
9 9 3.90x2.32 9.048
或使用base R
和read.table
mydf$res <- Reduce(`*`, read.table(text = sub("x", "X", mydf$ESPAC),
header = FALSE, sep="X"))
数据
mydf <- structure(list(ID = 1:9, ESPAC = c("2.70x2.20", "3.5X2", "3.6X2",
"3.00x1.33", "3.00x2.00", "3.00x2.50", "3.00x3.00", "3.5x2.14",
"3.90x2.32"), res = c(5.94, 7, 7.2, 3.99, 6, 7.5, 9, 7.49, 9.048
)), row.names = c(NA, -9L), class = "data.frame")