简体   繁体   中英

Combine multiple columns in R and new attribute calculates the mean of the row of data

I am attempting to combine multiple columns in my dataset however I have been using the unite() function and this does half of the work as it combines all the columns however I need it to calculate the mean of all the numbers.

Unite <- Complete_TrainingSet %>%
  unite(col = "PP1-3", PP1, PP2, PP3))

This was my code however I would like to know how would I also get it to calculate the mean?

Maybe you are looking for such a solution as you explicitly use unite . See this example with fake data. Here you unite all columns to one and then calculate the mean of that column.

library(tidyr)
df %>%
  unite("PP1-3", PP1, PP2, PP3, sep="") %>% 
  summarise(mean = mean(PP1-3))

Output

  mean
1  2.5

Data

df <- structure(list(PP1 = 1:10, PP2 = 11:20, PP3 = 21:30), class = "data.frame", row.names = c(NA, 
-10L))

Assuming you want the row means of the three columns. You can use rowMeans for this, like:

Unite <- Complete_TrainingSet %>%
  mutate(`PP1-3` = rowMeans(select(., PP1, PP2, PP3)))

With select you select the columns you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM