How do I add a new column named "Percentage" to the existing data set in R.Percentage is the average of the 6 exams as mentioned in the table below?

时间:2015-04-23 05:31:28

标签: r excel

Roll Subject Class Year Sec UT1 UT2 UT3 UT4 UT5  UT6
1   English   I   2001  A   70  96  65  61  71   60 
2   English   I   2001  A   82  80  77  99  72   44 
3   English   I   2001  A   64  66  54  56  79   42 
4   English   I   2001  A   64  92  40  96  52   63 
5   English   I   2001  A   97  56  52  94  72   86 
6   English   I   2001  A   64  67  91  48  73   61 

Also, please tell me how could I calculate the average marks in Excel for all the rows in one go?

I know how to do it row-wise but trying to figure out how it could be done in a single step for the entire rows.

1 个答案:

答案 0 :(得分:3)

You can create the new column as follows:

d$Percentage <- apply(d[,-1:-5], 1, mean)
d
#  Roll Subject Class Year Sec UT1 UT2 UT3 UT4 UT5 UT6 Percentage
#1    1 English     I 2001   A  70  96  65  61  71  60   70.50000
#2    2 English     I 2001   A  82  80  77  99  72  44   75.66667
#3    3 English     I 2001   A  64  66  54  56  79  42   60.16667
#4    4 English     I 2001   A  64  92  40  96  52  63   67.83333
#5    5 English     I 2001   A  97  56  52  94  72  86   76.16667
#6    6 English     I 2001   A  64  67  91  48  73  61   67.33333

Or you could use this more efficient method:

d$Percentage <- rowMeans(d[,-1:-5])