I have a dataset as follows:
` GN Datum Land AG..GKV. MTCR..GKV. NSGI..GKV. NSGII..GKV. WA..GKV. ML..GKV. Wert
8 11693 2012-01-05 Kenia 5A001f 159700
9 11710 2012-01-05 Indien 1C350.43 18752
10 11749 2012-01-05 Taiwan, Provinz von China 2B350g2 24000
11 11750 2012-01-05 Indien 2B201a1 2B001b2 370296
12 11751 2012-01-05 Serbien 2B201a 7200
13 11752 2012-01-05 Indien 4c 6037
14 11753 2012-01-05 Rumänien 2B001d 7830
15 11755 2012-01-06 China 2B201a1 215987
16 11756 2012-01-06 China 2B201a1 234736
17 11757 2012-01-06 Brasilien 2B231 69900
18 11758 2012-01-06 Brasilien 2B231 139800
19 11788 2012-01-07 Kongo 139800
GN
i a unique ID. As you can see, for each row, the variables AG..GKV.
until ML..GKV
hold one value at most, expect in the case where GN == 11750
.
I would like to combine these variables into one, but still know what the original variable name was, like so:
` GN Datum Land variable value Wert
8 11693 2012-01-05 Kenia WA..GKV. 5A001f 159700
9 11710 2012-01-05 Indien AG..GKV. 1C350.43 18752
...
In the case where there are two values per row as in GN == 11750
, it should look like this:
` GN Datum Land variable value Wert
11 11750 2012-01-05 Indien NSGII..GKV.\nWA..GKV. 2B201a1\n2B201a 370296
i.e., the "double" variable and value should be separated by a new line delimiter.
UPDATE: There is also a special case: When there is no value at all for one row. I want to preserve these (see GN == 19 above and below). variable
and value
should just be empty in this case.
` GN Datum Land variable value Wert
19 11788 2012-01-07 Kongo 370296
I have no clue how to achieve this and have already tried the reshape
package, but probably am too much of a R noob.
Here's a dput
(not the same cases as above, but with all three kinds of outcomes):
structure(list(GN = c(11789L, 11790L, 11791L, 11793L, 11794L,
11795L, 11796L), Datum = structure(c(15355, 15355, 15355, 15355,
15355, 15356, 15356), class = "Date"), Land = c("China", "Israel",
"Pakistan", "Iran, Islamische Republik", "Hong Kong", "Südafrika",
"Lettland"), AG..GKV. = c("2B350d4", "", "", "", "", "", ""),
MTCR..GKV. = c("", "", "", "", "", "", ""), NSGI..GKV. = c("",
"", "", "", "", "", ""), NSGII..GKV. = c("", "", "", "",
"", "", "2B201a1"), WA..GKV. = c("", "7A002a+b", "", "",
"3A001a2c", "6A003b4", "2B001b2"), ML..GKV. = c("", "", "",
"", "", "", ""), Wert = c(63720, 25672, 1608000, 10738, 202500,
13500, 374873)), .Names = c("GN", "Datum", "Land", "AG..GKV.",
"MTCR..GKV.", "NSGI..GKV.", "NSGII..GKV.", "WA..GKV.", "ML..GKV.",
"Wert"), row.names = 49:55, class = "data.frame")