简体   繁体   English

计算不包括R中某些列的行的平均值

[英]Calculate the mean of a row excluding certain columns in R

I am totally new to R and Stack Overflow so sorry if I ask this question in a weird way.我对 R 和 Stack Overflow 完全陌生,如果我以一种奇怪的方式问这个问题,我很抱歉。

I have a dataset which was obtained through surveys.我有一个通过调查获得的数据集。 In this survey there is a subset of variables that are grouped together and I would like to get the mean of a subset of these variables.在本次调查中,有一个分组在一起的变量子集,我想获得这些变量子集的平均值。

So for example: I want the averages of columns 18-22 of respondent/row 138 with na.rm=TRUE例如:我想要 na.rm=TRUE 的受访者/第 138 行的第 18-22 列的平均值

Is that possible?那可能吗?

Can easily be done with dplyr .使用dplyr可以轻松完成。 In the example df is the dataset name and columavg will be the column to store the new value in.在示例中df是数据集名称, columavg将是存储新值的列。

library(dplyr)

df = df %>%
     mutate(columavg = case_when(row_number() == 138 ~ rowMeans(.[18:22], na.rm=TRUE),
                                 TRUE ~ 0))

or if you want just that single value或者如果你只想要那个单一的价值

rowMeans(df[138,18:22], na.rm=TRUE)[[1]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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