如何执行以字符形式存储在R中的数学运算?
我有一张这样的桌子如何执行以字符形式存储在R中的数学运算?,r,regex,R,Regex,我有一张这样的桌子 structure(list(component = structure(1:4, .Label = c("a", "b", "c", "d"), class = "factor"), dimension = structure(c(1L, 3L, 4L, 2L), .Label = c("12*10*05", "30*30*20(2)+32*
structure(list(component = structure(1:4, .Label = c("a", "b",
"c", "d"), class = "factor"), dimension = structure(c(1L, 3L,
4L, 2L), .Label = c("12*10*05", "30*30*20(2)+32*34*04", "30*30*20+174*153*21+108*014*04",
"98*98*12(2)"), class = "factor")), class = "data.frame", row.names = c(NA,
-4L))
我需要在“dimension”列中执行数学运算,该列存储为字符并转换为整数。例如:“98*98*12(2)”
应存储为=(98*98*12)*2=230496
所需输出:
structure(list(component = structure(1:4, .Label = c("a", "b",
"c", "d"), class = "factor"), dimension = c(600L, 583110L, 230496L,
40352L)), class = "data.frame", row.names = c(NA, -4L))
您可以尝试下面的代码
> within(df, new.dimension <- sapply(gsub("(\\d)\\(","\\1*(",dimension),function(x) eval(parse(text = x))))
component dimension new.dimension
1 a 12*10*05 600
2 b 30*30*20+174*153*21+108*014*04 583110
3 c 98*98*12(2) 230496
4 d 30*30*20(2)+32*34*04 40352
>in(df,new.dimension)使用gsub
在括号和前面或后面的数字或括号之间插入*
。当您有有效语法时,parse
和eval
评估。此外,如果安全性是一个潜在问题,您应该清理输入(例如,确保它不包含字母字符)。gsub可能应该检查(
)之前的数字/空格,因为gsub(“\\(”,“*(”,“1+(2+3)”)
给出了“1+*(2+3)”,这是不可能的evaluated@Waldi谢谢你的评论,我想现在已经修好了