See image. This is a simplied example of my data.
So say I want to calculate the median of every row (1-7), but only containing of numbers in columns game1 and game2. So I want 7 median values, consisting of data in game1 and game2 only. What is my code in R to do this?

``````(exdf <- data.frame(g1 = 1:2, g2 = 2 + 1:2, g3 = rep(0, 2)))

# solution with R Base
(median_res <- apply(exdf, 1, \(x){
median(c(
x[["g1"]],
x[["g2"]]
))
}))

cbind(exdf,median_res)

# solution with tidyverse
library(tidyverse)

mutate(rowwise(exdf),
median_res = median(c_across(g1:g2)))``````

Can you explaine some of the codes you use?
For example, what do exdf and median_res mean?

they are simply names and could have used any characters and the code would have run the same.
exdf is a name I chose for an example data frame.
median_res is a name I chose for median results.

Thanks a lot
I have one question still, can you explain your first code: (exdf <- data.frame(g1 = 1:2, g2 = 2 + 1:2, g3 = rep(0, 2)))
What is g1 = 1:2 ? And g2 = 2 + 1:2 ? And g3 = rep(0, 2))?
I'm very new to R so thanks in advance!

They associate numbers with names.

You didnt provide numbers, so i chose my own

I attached a picture with numbers, can you see it?

We can see the picture, however this isn't very useful.
Typing in the numbers from the screenshot takes some time, hence it's easier to "invent" some numbers, just to show the concept of the solution.
This you can use with your dataset.

PS: The median of 2 samples is just the mean, you can use mean() as well..

Matthias gave a helpful explanation on my behalf; When faced with a screenshot of 'data' I go one of two ways; if its a small effort that I accept I will generate my own example data and not worry about it. If it would be particularly annoying (or impossible) to stand up the screenshotted data as data in my R session I write to the user :

Hello,
I'm sure you shared this image with the best intentions, but perhaps you didnt realise what it implies.
If someone wished to use example data to test code against, they would type it out from your screenshot...

This is very unlikely to happen, and so it reduces the likelihood you will receive the help you desire.
Therefore please see this guide on how to reprex data. Key to this is use of either datapasta, or dput() to share your data `as code`
FAQ: How to do a minimal reproducible example ( reprex ) for beginners

This topic was automatically closed 21 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.