eagles02
eagles02

Reputation: 65

Adding columns to a data frame in R

I have the below data frame:

  Name      id   Quiz1 Exam1 Exam2 Quiz2 Exam3
1 Susan   123412  50    47    33    67    79
2 John    548963  38    61    75    59    65
3 Bob     234563  89    97    85    88    92
4 Bill    429591  72    73    74    75    76
5 Mary    245887  92    95    79    89    90
6 Paul    97522   99     3    55    60    72

and want to add 2 columns. Quiz Average and Exam Average. I have been having a hard time getting any code to work, anyone have any ideas?

Upvotes: 2

Views: 184

Answers (2)

LearnR
LearnR

Reputation: 336

The transform function does get the job done, but creating columns in R can be accomplished very easily without the use of the transform function.

Adding your columns can also be accomplished by:

> df$QuizAverage = (df$Quiz1 + df$Quiz2) / 2

> df$ExamAverage = (df$Exam1 + df$Exam2 + df$Exam3) / 3

This site provides a pretty good reference for manipulating dataframes. HowToinR.weebly.com

Upvotes: 1

Jilber Urbina
Jilber Urbina

Reputation: 61154

You mean something like this...?

> transform(df, 
+           QuizAverage=rowMeans(cbind(Quiz1, Quiz2)),
+           ExamAverage=rowMeans(cbind(Exam1, Exam2, Exam3)))
   Name     id Quiz1 Exam1 Exam2 Quiz2 Exam3 QuizAverage ExamAverage
1 Susan 123412    50    47    33    67    79        58.5    53.00000
2  John 548963    38    61    75    59    65        48.5    67.00000
3   Bob 234563    89    97    85    88    92        88.5    91.33333
4  Bill 429591    72    73    74    75    76        73.5    74.33333
5  Mary 245887    92    95    79    89    90        90.5    88.00000
6  Paul  97522    99     3    55    60    72        79.5    43.33333

Upvotes: 4

Related Questions