Coding help for rearrangement of data frame.

Good day,

#I’ve created hypothetical data for drug X and drug Y whereby both drug have the ability to have HbA1c reduction.

set.seed(10)

drugx= rnorm(50, mean = 0.1, sd=0.02)

set.seed(11)

drugy= rnorm(50, mean=0.15, sd=0.03)

#And created a data frame, compare drugs (comdrug) of 50 patients for each drug.

comdrug= data.frame("ID"=c(1:50), "DrugX"=drugx, "DrugY"=drugy)

whereby the data would look like this

head(comdrug)

> head(comdrug)

ID DrugX DrugY

1 1 0.10037492 0.1322691

2 2 0.09631495 0.1507978

3 3 0.07257339 0.1045034

4 4 0.08801665 0.1091204

5 5 0.10589090 0.1853547

6 6 0.10779589 0.1219755

Is there anyway of coding if I could arrange like this?

30%20PM

You can use the gather() function from the tidyr package to get the following result.

set.seed(10)

drugx= rnorm(50, mean = 0.1, sd=0.02)

set.seed(11)

drugy= rnorm(50, mean=0.15, sd=0.03)

#And created a data frame, compare drugs (comdrug) of 50 patients for each drug.

comdrug= data.frame("ID"=c(1:50), "DrugX"=drugx, "DrugY"=drugy)
head(comdrug)
#>   ID      DrugX     DrugY
#> 1  1 0.10037492 0.1322691
#> 2  2 0.09631495 0.1507978
#> 3  3 0.07257339 0.1045034
#> 4  4 0.08801665 0.1091204
#> 5  5 0.10589090 0.1853547
#> 6  6 0.10779589 0.1219755
library(tidyr)
comdrug2 <- gather(comdrug, key = DrugType, value = Reduction, DrugX, DrugY)

head(comdrug2)
#>   ID DrugType  Reduction
#> 1  1    DrugX 0.10037492
#> 2  2    DrugX 0.09631495
#> 3  3    DrugX 0.07257339
#> 4  4    DrugX 0.08801665
#> 5  5    DrugX 0.10589090
#> 6  6    DrugX 0.10779589

The drugy values are listed farther down the table after the drugx values.

1 Like

Maybe I'm missing something, but how are you getting the Hba1c reduction values of the picture from the previous comdrug object?

Or, are they results of different random generations and hence unrelated?

awesome. thanks mate.

If your question's been answered (even by you!), would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it:

1 Like

yes correct, both are un related.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.