简体   繁体   中英

How to do calculations on a column of a data frame using values contained in another data frame in R?

I have 2 data frames: one with experimental data and one with values of some constants. Experimental data and constants are separated by categories (a and b). I would like to include a new column in the experimental data frame that is the result of the following calculation:

z = k*y

To do this, I'm using the dplyr package and the mutate() function, but I'm not getting the expected result. Does anyone have any tips or suggestions, even if it is necessary to use another 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)

I did this:

a = c()
for(i in unique(df$Category)){
  a = c(a,df[df$Category==i,"y"]*Constant[Constant$Category==i,'k'])
}
df$z=a

result:

   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

I don't know if it was what you're looking for. Juste keep in mind that this works if your df is sorted by the category column

if you don't like for loop, here is a lapply version:

df$z =unlist( lapply(unique(df$Category), function(i){return(df[df$Category==i,"y"]*Constant[Constant$Category==i,'k'])}))

if the data isn't sorted by category:

df$z=unlist(lapply(1:nrow(df),function(i){ return(df[i,"y"]*Constant[Constant$Category==df[i,"Category"],'k'])}))

With dplyr you can do the following:

library(dplyr)

left_join(df, Constant, by = c("Category")) %>%
  mutate(z = k * y) %>%
  select(-k)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM