-1

I'd like to transpose this data frame:

First Dataframe Rstudio

So I use this line of code

perCountry <- data.frame(t(perEnergy))

And I get this result:

Second Dataframe Rstudio

But I'd like it without the first row (X1,X2,X3...) and with the country name at this spot. How could I do ?

camille
  • 16,432
  • 18
  • 38
  • 60
Daunter
  • 71
  • 4
  • 1
    Please don't post pictures of data here. Here are some excellent tips on how to make a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610). That way you can help others to help you! – dario Feb 11 '20 at 14:10

1 Answers1

0

The problem is that you would have two different columns for each country: one for % and one for MW. It might be easier to work with if you have two different data frames:

percentages <- data.frame(t(perEnergy[perEnergy$a == "%",]))
MW          <- data.frame(t(perEnergy[perEnergy$a == "[MW]",]))

You can turn the first row into column names like this:

names(percentages) <- percentages[1,]
names(MW)          <- MW[1,]

Then remove the unwanted first row like this:

percentages <- percentages[-1,]
MW          <- MW[-1,]

Finally, if you want to stick them back together again, you will need unique row names. You might do something like this:

rownames(percentages) <- paste0(rownames(percentages), "_percent")
rownames(MW)          <- paste0(rownames(MW), "_MW")

So that finally you can join the two dataframes together:

perCountry <- rbind(percentages, MW)

Unfortunately I cannot test the above code, since you did not post any usable data in your question.

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87