R - Adding vector from one dataframe as column to another dataframe

Viewed 53

I have two dataframes and want to add a specific vector from one as a column to another, for multiplication purposes OR how can I multiply data from one dataframe to a specific vector from another?

Example

 library (dplyr)

df <- data.frame (name = c("A", "B", "C", "D", "E"),
                       area = c(1,2,3,4,5),
                       yield = c(10, 20, 30, 40, 50))
    
df2 <- data.frame (application = c("test", "current", "future"),
                       number = c(5,10,15))

The intended result is e.g. get the value for "current" in df2 and create a new column on df named "number", that will be multiplied with the other columns in df and generate the column "calculation" - excel example on how df would look like at the end below:

enter image description here

I tried

df$number <- df2 %>% 
  filter(application == "current") %>% 
  select(number)

But I get an Error in $<-.data.frame(*tmp*, number, value = list(number = 10)) : replacement has 1 row, data has 5

I know that I could do

df$number <- df2[2,2]

But I want it to be specifically related to "current" (as I tried to do with dplyr). This is only an example - in reality, df2 is a big file and the order can change when people are adding more data.

1 Answers

Here is a base R approach -

df$number <- df2$number[df2$application == "current"]
df$calculation <- with(df, area * yield * number)
df

Or if you prefer dplyr -

library(dplyr)

df <- df %>%
  bind_cols(df2 %>%
  filter(application == "current") %>%
  select(number)) %>%
  mutate(calculation = area * yield * number)

df

#  name area yield number calculation
#1    A    1    10     10         100
#2    B    2    20     10         400
#3    C    3    30     10         900
#4    D    4    40     10        1600
#5    E    5    50     10        2500
Related