I have two dataframes df1
and df2
and `df2':
df1 = structure(list(Day = c(19L, 20L, 20L, 20L, 20L, 21L, 21L, 21L,
21L, 21L, 21L, 21L, 22L, 22L, 22L, 22L, 22L, 22L, 22L, 22L),
Month = c(9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9), Year = c(2004, 2004, 2004, 2004, 2004, 2004,
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004,
2004, 2004, 2004, 2004), Date = structure(c(12680, 12681,
12681, 12681, 12681, 12682, 12682, 12682, 12682, 12682, 12682,
12682, 12683, 12683, 12683, 12683, 12683, 12683, 12683, 12683
), class = "Date")), row.names = c("text1", "text2", "text3",
"text4", "text5", "text6", "text7", "text8", "text9", "text10",
"text11", "text12", "text13", "text14", "text15", "text16", "text17",
"text18", "text19", "text20"), class = "data.frame")
Day Month Year Date
text1 19 9 2004 2004-09-19
text2 20 9 2004 2004-09-20
text3 20 9 2004 2004-09-20
text4 20 9 2004 2004-09-20
text5 20 9 2004 2004-09-20
text6 21 9 2004 2004-09-21
text7 21 9 2004 2004-09-21
text8 21 9 2004 2004-09-21
text9 21 9 2004 2004-09-21
text10 21 9 2004 2004-09-21
text11 21 9 2004 2004-09-21
text12 21 9 2004 2004-09-21
text13 22 9 2004 2004-09-22
text14 22 9 2004 2004-09-22
text15 22 9 2004 2004-09-22
text16 22 9 2004 2004-09-22
text17 22 9 2004 2004-09-22
text18 22 9 2004 2004-09-22
text19 22 9 2004 2004-09-22
text20 22 9 2004 2004-09-22
df2 = structure(list(days = structure(c(12680, 12681, 12682, 12683,
12684, 12685, 12686, 12687, 12688, 12689, 12690, 12691, 12692,
12693, 12694), class = "Date"), week = c(3, 3, 3, 4, 4, 4, 4,
4, 4, 4, 4, 4, 1, 1, 1)), row.names = c(NA, -15L), class =
"data.frame")
days week
1 2004-09-19 3
2 2004-09-20 3
3 2004-09-21 3
4 2004-09-22 4
5 2004-09-23 4
6 2004-09-24 4
7 2004-09-25 4
8 2004-09-26 4
9 2004-09-27 4
10 2004-09-28 4
11 2004-09-29 4
12 2004-09-30 4
13 2004-10-01 1
14 2004-10-02 1
15 2004-10-03 1
As you can see df1
is longer than df2
and contains all the "dates" in df2
. What I would like to get is a code that says: if the date is df1
is the same as the date in df2
, then give me the week
number. I manage to do it individually:
if (df1$Date[1] == df2$days[1]) df2$week[1]
if (df1$Date[2] == df2$days[2]) df2$week[2]
if (df1$Date[3] == df2$days[2]) df2$week[2] # this is the issue: df1 is longer than df2 since it repeats dates more than ones
if (df1$Date[4] == df2$days[2]) df2$week[2] # same as above
...
The problem is that when I try to loop for every element in df1
and df2
I fail since the two have different length since df1
repeats the same date n times. So I would need a loop that takes care of the repetions of dates in df1
. Yet I got stuck here:
for (i in length(# don't know how to handle the different length)) {
if (df1$Date[1] == df2$days[1]) df2$week[1]
}
Can anyone help me sort this out?
Thanks!
Aucun commentaire:
Enregistrer un commentaire