gpt4 book ai didi

R 使用查找表替换字符串中的多个变量

转载 作者:行者123 更新时间:2023-12-04 12:11:22 24 4
gpt4 key购买 nike

我正在使用 2 个数据帧,作为示例:
DF1 是主表,其中一列包含通常具有变量的方程

DF1 <- read.table(text = 
"Unit Year Equation
1 2020 'x+2*y'
1 2021 'x+2*y'
1 2022 'x+2*y'
2 2020 'x'
3 2020 'max(y^2, y+2*z)'
3 2021 'max(y^2, y+2*z)'
4 2020 '5'
5 2020 '(x/y)+z'",
header = TRUE, stringsAsFactors = FALSE)
DF2 是将值分配给给定年份的变量的引用或查找表
DF2 <- read.table(text = 
"Year Variable Value
2020 x 10
2021 x 15.5
2022 x 50
2020 y 1
2021 y 2
2022 y 3.5
2020 z 20
2021 z 34
2022 z 11",
header = TRUE, stringsAsFactors = FALSE)
目标是匹配 2 个数据帧之间的变量和年份,以便在应用 eval(parse(text=Equation)) 或任何类似内容后可以得出下表:
Unit     Year  Equation
1 2020 12
1 2021 19.5
1 2022 57
2 2020 10
3 2020 41
3 2021 70
4 2020 5
5 2020 30
目前我正在使用 for 和 if-else 循环来匹配年份并逐行替换变量。它工作正常,但运行它变得非常慢,因为 DF1 可能包含具有多个变量的数千行。我可以使用其他功能来实现相同的输出吗?
编辑 - 在提到的循环中添加以帮助进行比较:
library(dplyr)
library(reshape2)
DF2 = dcast(DF2, Year~Variable, value.var='Value')

#Adding in this line to avoid replacing "x" in "max":
DF1$Equation = gsub("max","placeholder",DF1$Equation)

for(i in 1:nrow(DF1)) {
for (j in 1:nrow(DF2)) {
if (DF1[i,]$Year==DF2[j,]$Year) {
#Every variable would be declared here:
DF1[i,]$Equation = gsub("x",DF2[j,]$x,DF1[i,]$Equation)
DF1[i,]$Equation = gsub("y",DF2[j,]$y,DF1[i,]$Equation)
DF1[i,]$Equation = gsub("z",DF2[j,]$z,DF1[i,]$Equation)
}
}
}
#Returning the function:
DF1$Equation = gsub("placeholder","max",DF1$Equation)

Results_DF1 = DF1 %>% rowwise() %>%
mutate(Equation = eval(parse(text=Equation)))

最佳答案

你可以这样做:

left_join(DF1, DF2, 'Year') %>%
pivot_wider(c(Unit,Year,Equation),Variable, values_from = Value) %>%
rowwise() %>%
mutate(a = eval(parse(text = Equation)))

Unit Year Equation x y z a
<int> <int> <chr> <dbl> <dbl> <dbl> <dbl>
1 1 2020 x+2*y 10 1 20 12
2 1 2021 x+2*y 15.5 2 34 19.5
3 1 2022 x+2*y 50 3.5 11 57
4 2 2020 x 10 1 20 10
5 3 2020 max(y^2, y+2*z) 10 1 20 41
6 3 2021 max(y^2, y+2*z) 15.5 2 34 70
7 4 2020 5 10 1 20 5
8 5 2020 (x/y)+z 10 1 20 30

关于R 使用查找表替换字符串中的多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67784322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com