Changing rows and columns

I want redesing my table – change the rows, order numbers, columns and etc. I have created a sample in excel that what I want to get as well as I showed a screenshot of data that what I have right now.Can you please help me?

R data
enter image description here

Excel data (what I want to get)
enter image description here

I have tried different methods – dcast, transpose and etc. but they didn’t work.

>Solution :

You can likely use some command on import (ie, header = TRUE) but if this is how your data look:

set.seed(123)
df <- data.frame(V1 = c("MFST", runif(5)),
                 V2 = c("ATVI", runif(5)),
                 V3 = c("AMOT", runif(5)))
rownames(df) <- c("Years", 2015:2019)

It means (1) your first row is your column names and (2) your row names are your year values. So you can do this in base R:

colnames(df) <- df[1,] # rename columns
df$years <- rownames(df) # create year variable from rownames
df <- df[-1,] # remove unneeded first column

Output:

#      MFST ATVI AMOT years
# 2015 0.29 0.05 0.96  2015
# 2016 0.79 0.53 0.45  2016
# 2017 0.41 0.89 0.68  2017
# 2018 0.88 0.55 0.57  2018
# 2019 0.94 0.46 0.10  2019

Again though, I would check the import step. If you provide more info on that I can edit to provide more advice. Good luck!

Leave a Reply