0

I am trying to add the value from each row of the column ConversionFactor (from df2) to new column ($value) of df1 when the value of same row of column (NameSize) from df1 and df2 are equals.

See the code:

df1$value[df2$NameSize == df1$NameSize] <- df2$ConversionFactor[df1$NameSize == df2$NameSize]

the two dataframe doesnt have same lenght, I have this warning message:

Warning messages: 1: In data_merged_2018_2019_1$NameSize == final_carbonfactor$NameSize : longer object length is not a multiple of shorter object length 2: In if (data_merged_2018_2019_1$NameSize == final_carbonfactor$NameSize) { : the condition has length > 1 and only the first element will be used

Grg Lulu
  • 11
  • 5

1 Answers1

0

If you are familiar with the tidyverse way of doing things, they have sqlite join methods available. Your solution would end up like this:

library(dplyr)
d1.fixed <- d1 %>% left_join(
                       select( d2, NameSize, ConversionFactor )
                   ) %>% rename( Value = ConversionFactor ) %>%
               distinct( NameSize, Value, .keep_all=TRUE )

left_join "joins" the data by a column you specify, or detects it automatically and informs you. I also made sure to make sure d2 only contains the NameSize and ConversionFactor column so you don't bring in what else is in it.

EDIT: added library call and some more explanation

Sirius
  • 5,224
  • 2
  • 14
  • 21
  • Hei, I did use the left_join function but I ended up with more row (e.g., 2015) on the new data frame than it should be at the beginning (e.g.,1934) because some row are duplicated which I do not understand why. that is why I was wondering to do it differently and not use the left_ join function of dplyr :/ – Grg Lulu Mar 08 '21 at 20:52
  • you should be able to use `distinct` (https://dplyr.tidyverse.org/reference/distinct.html) as shown now in the edited code. Just give it the columns which you mean should define uniqueness. But if you don't understand why you had duplicates in the first place, I recomend you try to figure out why first. – Sirius Mar 08 '21 at 21:44
  • I fount, i have twice value at the df2 than it duplicates it... thanks very much:) – Grg Lulu Mar 08 '21 at 22:31