Insert vector value of a data.frame into another data.frame

Asked

Viewed 1,214 times

1

I have two data frames. The first one has 2185 observations and the second one has only 9.

The first data frame, whose name is dados, contains the following variables:: local, parc, arv, DAP, Ht, Hf, epiteto and genero.

The second, named after coordg contains parcela, longitude, latitude and Eg.

inserir a descrição da imagem aqui

I would like to insert the values of the environmental variable Eg of data frame coordg in the data frame dados, repeating the value of Eg for each arv, according to the name of parc common among data frames, as below:

   Local    parc   arv  DAP     Ht    Hf   copa      genero       epiteto      Eg
  varzea    MZVT2   1   11.777  14.1  13.5  0.6      Euterpe       oleracea    0.016
  varzea    MZVT2   2   13.782  17.4  14.0  3.4      Euterpe       oleracea    0.016
  varzea    MZVT2   3    9.326  11.1   4.0  7.1      Euterpe       oleracea    0.016
  varzea    MZVT2   4   25.305  20.8  12.0  8.8   Calycophyllum  spruceanum    0.016
  varzea    MZVT2   5   10.345  11.2   4.0  7.2   Indeterminada Indeterminada  0.016
  • You need a left_join, see the answers to this question: https://answall.com/questions/124319/busca-valores-em-um-data-frame-e-addir-outro-r/124326#124326

2 answers

0


First I suggest transforming the name of the split column into Parc, to be the same in the two dataframes:

names(coordg)[1] <- "parc"

The function merge can help you. The code would look like this:

dados2 <- merge(dados, coordg[ ,c("parc","Eg")], by="parc")

Recalling that the dados 2 will be in the new dataframe with all columns of the dados more the Eg of each parc.

0

You can use the function subsetto verify which value of the variable parc you need to use:

subset(coordg, parcela %in% dados$parc)

this will return the required field value parcela dataframe coordg

So, you only need to add a new column in the dataframe and fill it with this value:

dados$eg <- subset(coordg, parcela %in% dados$parc)[4]

Or else

dados$eg <- subset(coordg, parcela %in% dados$parc)["Eg"]

Where paragraph 4 refers to the number of the column in which the values of eg in the dataframe coordg.

This will only work when the dataframe dados has only the same value for parc on all lines. If it has different values, it will be necessary to modify (I think a forcould already solve if necessary). If this is the case, please comment that I will try to see how to solve.

  • I’ll check. But thanks for the help!

  • When I went to add the new column in the dataframe, an error appeared in the substitution, stating that Eg consists of 9 lines and the data is 2538, so you cannot perform the operation: Error in $<-.data.frame(*tmp*, "Eg", value = list(Eg=c(0.0167105529787358, : Placement has 9 Rows, date has 2538

Browser other questions tagged

You are not signed in. Login or sign up in order to post.