![](/img/trans.png)
[英]R How to update a column in data.frame using values from another data.frame
[英]How to do calculations on a column of a data frame using values contained in another data frame in R?
我有 2 個數據框:一個帶有實驗數據,一個帶有一些常數的值。 實驗數據和常數按類別(a 和 b)分開。 我想在實驗數據框中包含一個新列,它是以下計算的結果:
z = k*y
為此,我使用了dplyr
package 和mutate()
function,但我沒有得到預期的結果。 有沒有人有任何提示或建議,即使需要使用另一個 package?
library(dplyr)
Category <- c("a", "b")
k <- c(1, 2)
# Data frame with the constants for each category
Constant <- data.frame(Category, k)
x <- seq(0,5,1)
df <- expand.grid(x = x,
Category = Category)
# Data frame with the experimental resultas
df$y <- seq(1,12,1)
# Failed attempt to calculate z separated by categories
df %>%
group_by(Category) %>%
mutate(z = Constant*y)
我這樣做了:
a = c()
for(i in unique(df$Category)){
a = c(a,df[df$Category==i,"y"]*Constant[Constant$Category==i,'k'])
}
df$z=a
結果:
x Category y z
1 0 a 1 1
2 1 a 2 2
3 2 a 3 3
4 3 a 4 4
5 4 a 5 5
6 5 a 6 6
7 0 b 7 14
8 1 b 8 16
9 2 b 9 18
10 3 b 10 20
11 4 b 11 22
12 5 b 12 24
不知道是不是你要找的。 請記住,如果您的df
按類別列排序,則此方法有效
如果你不喜歡 for 循環,這里有一個lapply
版本:
df$z =unlist( lapply(unique(df$Category), function(i){return(df[df$Category==i,"y"]*Constant[Constant$Category==i,'k'])}))
如果數據未按類別排序:
df$z=unlist(lapply(1:nrow(df),function(i){ return(df[i,"y"]*Constant[Constant$Category==df[i,"Category"],'k'])}))
使用 dplyr 您可以執行以下操作:
library(dplyr)
left_join(df, Constant, by = c("Category")) %>%
mutate(z = k * y) %>%
select(-k)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.