0

programming language: R

i have one dataframe that provides experimental observations (several observations correspond to the same participant id) and the other dataframe that includes info about these participants. how can i copy this info from dataframe 2 to dataframe 1 so that whenever the id is the same, the info is added to the corresponding row?

i guess i need something like a loop where i search for matching id's and if they match, the info is copied. but no clue how to do it as i'm totally new to programming T.T

mipmip
  • 1
  • please, provide a reproducible example of your data frames and what the desired result would look like - this way you increase your chances of receiving an answer – Kasia Kulma Aug 06 '19 at 20:44
  • This has been asked a number of times and since you are a new user of R I think you might be first interested in a base R solution: [https://stackoverflow.com/a/1300618/3602983](https://stackoverflow.com/a/1300618/3602983) But you should know there are also a number of libraries that handle this as well in simpler, and more efficient ways and are included in that thread linked above. Of particular note are tidyverse (dplyr, tidyr, +) and data.table. – Geoffrey Grimm Aug 06 '19 at 20:44

1 Answers1

0

I would use merge or the join functions in the tidyverse suite of packages:

df1 <- data.frame(
  'id' = 1:5,
  'y1' = LETTERS[1:5])

df2 <- data.frame(
  'id' = sample(1:5, size = 20, replace = TRUE), 
  'x1' = rnorm(20,0,1))

merge(df1, df2, by = 'id')

library(tidyverse)
left_join(df1, df2, 'id')
rg255
  • 4,119
  • 3
  • 22
  • 40