简体   繁体   中英

Sum or mean of certain element in data frame in R

I have a data frame that look like this:

  k v 2002 2006 2010
1 a x 79.1 80.2 83.2
2 a y 75.1 76.2 79.3
3 a z 74.7 75.8 79.0
4 b x 82.8 85.9 87.6
5 b y 81.1 83.5 85.1
6 b z 80.5 83.1 84.6

etc. What I need is the mean of the numeric values for every row, ie I want it to look like this:

  k v    tot
1 a x 80.833
2 a y 76.867
3 a z 76.500
4 b x 85.433
5 b y 83.233
6 b z 82.733

I don't want to keep the original values, just the means. I know about rowMeans but as far as I know I can't (and don't want to) use it since it is averaging the whole row, not just the three last columns. I tried to use

rowMeans(subset(df,select=3:5))

but then I only get the numerical values and loose the variables k and v . Does anyone know a convenient way to get the mean over just some of the elements in a row?

dplyr::mutate(df, tot= (`2002`+`2006`+`2010`)/3) 

should work too.

This will preserve the first two columns of variables as you intended, and append a column named tot that is = the mean of the three 'years' cols.

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