英文:
Add a column to data frame using a function referencing another data frame in R
问题
对于每个人,对于每个t值,我需要取该t值的天花板值,找到df2中该人和天花板t值的行,然后取exp(c1b1+c2b2+c3*b3)的行,其中b1=1,b2=1,b3=1。
所以对于Ben:
ceiling(1.1)=2,在df2中对于Ben和t=2,我们得到exp(1b1+0b2+0*b3)
ceiling (2.3) = 3,在df2中对于Ben和t=3,我们得到exp(1b1+0b2+1*b3)
然后exp(1b1+0b2+0b3) + exp(1b1+0b2+1b3)
对于Lucy:
ceiling(1.2) = 2,在df2中对于Lucy和t=2,我们得到exp(0b1+0b2+1*b3)
ceiling(2.5) = 3,在df2中对于Lucy和t=3,我们得到exp(0b1+0b2+2*b3)
ceiling(2.7) = 3,在df2中对于Lucy和t=3,我们得到exp(0b1+0b2+2*b3)
然后exp(0b1+0b2+1b3) + exp(0b1+0b2+2b3) + exp(0b1+0b2+2*b3)
英文:
df1=
Name t
1 Ben 1.1
2 Ben 2.3
3 Lucy 1.2
4 Lucy 2.5
5 Lucy 2.7
df2 =
Name t c1 c2 c3
1 Ben 1 0 0 0
2 Ben 2 1 0 0
3 Ben 3 1 0 1
4 Lucy 1 1 1 0
5 Lucy 2 0 0 1
6 Lucy 3 0 0 2
For each person, for each t value, I need to take the ceiling of that t value, find the row with that person and ceiling t value in df2 and take exp(c1b1+c2*b2+c3*b3) of that row where b1=1, b2=1, b3=1.
So for Ben:
ceiling(1.1)=2, in df2 for Ben and t=2 we get exp(1b1+0b2+0*b3)
ceiling (2.3) = 3, in df2 for Ben and t=3 we get exp(1b1+0b2+1*b3)
and then exp(1b1+0b2+0b3) + exp(1b1+0b2+1b3)
For Lucy:
ceiling(1.2) = 2, in df2 for Lucy and t=2 we get exp(0b1+0b2+1*b3)
ceiling(2.5) = 3, in df2 for Lucy and t=3 we get exp(0b1+0b2+2*b3)
ceiling(2.7) = 3, in df2 for Lucy and t=3 we get exp(0b1+0b2+2*b3)
and then exp(0b1+0b2+1b3) + exp(0b1+0b2+2b3) + exp(0b1+0b2+2*b3)
答案1
得分: 2
使用dplyr
包,我们可以通过left_join
,然后使用mutate
获取每一行的值,最后使用summarize
来获取总和:
library(dplyr)
# 将b1、b2和b3设置为1
b1 <- b2 <- b3 <- 1
df1 %>%
mutate(ceiling_t = ceiling(t)) %>%
left_join(df2, by = c(Name = "Name", ceiling_t = "t")) %>%
mutate(result = exp(c1 * b1 + c2 * b2 + c3 * b3)) %>%
group_by(Name) %>%
summarize(result = sum(result))
#> # A tibble: 2 x 2
#> Name result
#> <chr> <dbl>
#> 1 Ben 10.1
#> 2 Lucy 17.5
创建于2023-02-15,使用reprex v2.0.2。
英文:
Using the dplyr
package, we could do this via a left_join
, then mutate
to get each row's value and finally summarize
to get the sum:
library(dplyr)
# Set b1, b2 and b3 to 1
b1 <- b2 <- b3 <- 1
df1 %>%
mutate(ceiling_t = ceiling(t)) %>%
left_join(df2, by = c(Name = "Name", ceiling_t = "t")) %>%
mutate(result = exp(c1 * b1 + c2 * b2 + c3 * b3)) %>%
group_by(Name) %>%
summarize(result = sum(result))
#> # A tibble: 2 x 2
#> Name result
#> <chr> <dbl>
#> 1 Ben 10.1
#> 2 Lucy 17.5
<sup>Created on 2023-02-15 with reprex v2.0.2</sup>
答案2
得分: 2
在基本的R中:
a <- merge(transform(df1, t = ceiling(t)), df2)
rowsum(exp(as.matrix(a[-(1:2)])%*%c(b1 = 1,b2 = 1,b3 = 1)), a$Name)
[,1]
Ben 10.10734
Lucy 17.49639
英文:
in base R:
a <- merge(transform(df1, t = ceiling(t)), df2)
rowsum(exp(as.matrix(a[-(1:2)])%*%c(b1 = 1,b2 = 1,b3 = 1)), a$Name)
[,1]
Ben 10.10734
Lucy 17.49639
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论