0

I assume this is rather straightforward, but unfortunately I haven't been able to figure out the solution. I found hints here and here, but they weren't solving the issue.

I have a dataframe with election results (x.melt; several thousand rows) and another dataframe (parties.bih) which contains only the party names and the ethnic affiliations. The two dataframes have different dimensions.

dataframe parties.bih

                           party ethnicity
1                        BPS         B
2                       SBiH         B
3                        SDP         X
4                        SDS         S
5                        DNZ         B
6                        SDA         B
7                        PDP         S
8                        DNS         S
9                      NSRzB         C
10                      SNSD         S
11 HDZ.1990.HZ.HSS.HKDU.HDU.         C
12                   HDZ.HNZ         C
13                    SBBBiH         B
14                    HDZBiH         C
15        Croatian.Coalition         C

All I want to do is to add the ethnic affiliation of each party (in dataframe parties.bih) to the election results (in dataframe x.melt).

When I try this command, the ethnic affiliations are added, but not in accordance with each party.

x.melt$ethnicity[x.melt$party==parties.bih$party] <- parties.bih$ethnicity

When I try the merge command, the row "party" disappears. I could of course duplicate the party column, but there must be a more straightforward solution.

tt <- merge(x.melt, parties.bih, by.x="party", by.y="party", all.x=TRUE)

I am still rather new to R, and assume that this is quite easy actually, but I have simply not figured it out. Many thanks.

4

1 回答 1

0

合并应该可以工作,用于合并的列包含在输出数据框中。这至少适用于我的示例数据框:

class<- c("A","B","C","D"); var1<- 1:4; var2<- 30:33
df1<- data.frame(class,var1)
df2<- data.frame(class,var2)
tt <- merge(df1, df2, by="class",all=TRUE)

出去:

> tt

class var1 var2
1     A    1   30
2     B    2   31
3     C    3   32
4     D    4   33

还是我误解了你的问题?

于 2013-09-10T13:52:02.570 回答