Morgan Wood
Morgan Wood

Reputation: 15

Is there a way to get the mean of only certain values in a data frame rather than whole rows or columns?

Image of data frame example I need to get the mean of specific values such as at coordniate points [1,1] [1,5] [1,9] so it would be absorbance_one_norm value at row 1 5 and 9

Would it make more sense to create a new data frame? Not sure how to grab specific values by doing that or just using a mean function. Any help is appreciated

An example of the output I want would be a new data frame with mean values

absorbance_1_mean,  absorbance_2_mean
.33333              .3333
.33333               .33333
.3333                .3333

Edit: I am new to r so please be kind

Upvotes: 1

Views: 1142

Answers (2)

mikebader
mikebader

Reputation: 1289

If you want the mean for the same rows across columns, the following (using base R) will work by subsetting the rows and then taking the means of each row.

library(tibble)
# Make example data
df <- tibble(!!!lapply(1:10, function(x) runif(100)), 
             .name_repair = ~paste0("absorbance", 1:10))
# Make vector containing desired rows
desired_rows <- c(1, 5, 9)
# Take the mean down each column 
apply(df[desired_rows, ], 2, mean)

Upvotes: 1

akrun
akrun

Reputation: 887088

We can use row/column index to extract the elements and get the mean

mean(df1[cbind(c(1, 1, 1, 2, 2, 2), c(1, 5, 9, 1, 5, 9))])

Upvotes: 1

Related Questions