maximusdooku
maximusdooku

Reputation: 5512

How can I operate on a particular column?

I know how to do it manually. But I would like to do it in a smart way. I am very confused how to use the apply functions.

All I want to do is sum the values of frequency column and divide every number by this sum. Also,I have to do this for a large number of data frames.

class Frequency
A  1
B  1
C  1
D  1
E  1
F  1
G  1
H  1
I  1
J  1

Expected output since Sum = 10.

class Frequency
A  .1
B  .1
C  .1
D  .1
E  .1
F  .1
G  .1
H  .1
I  .1
J  .1

Also, I have 10 such dataframes, say df1,df2,....,df10.

Upvotes: 0

Views: 40

Answers (1)

MrFlick
MrFlick

Reputation: 206177

With sample data frames in a list like this

mydata<-replicate(2, data.frame(
    class=letters[1:5], 
    Frequency=rpois(5, 4)), 
simplify=FALSE)

You can use an lapply to iterate over the list of data.frames

lapply(mydata, function(x) transform(x, Frequency=Frequency/sum(Frequency)))

Upvotes: 2

Related Questions