How to apply a code for multiple columns?
1
0
Entering edit mode
2.4 years ago

Hi. I am new to R and have the following example code that I wish to apply for every column in my data.

data(economics, package="ggplot2")
economics$index <- 1:nrow(economics)
loessMod10 <- loess(uempmed ~ index, data=economics, span=0.10)
smoothed10 <- predict(loessMod10)
plot(economics$uempmed, x=economics$date, type="l", main="Loess Smoothing and Prediction", xlab="Date", ylab="Unemployment (Median)")
lines(smoothed10, x=economics$date, col="red")

Could someone please suggest how this would be possible?

Thanks!

ggplot2 R • 829 views
ADD COMMENT
0
Entering edit mode

read about apply

ADD REPLY
0
Entering edit mode

Thank you, but I am stuck at writing an apply function at saving the output from loess and plot. Could you please help me with that?

ADD REPLY
1
Entering edit mode
2.4 years ago
JJDollar ▴ 130

What function do you want to apply to each column exactly? To apply a function to each column, you can use something like this.

apply(m, 2, function(x) max(x))

Where m = matrix/data.frame 2 = means to apply the function column wise (use 1 to apply function row-wise). And the function you want to apply is the third input. In the example, this code would just give the max value for each column.

This link maybe helpful! https://www.r-bloggers.com/2012/12/using-apply-sapply-lapply-in-r/

ADD COMMENT
0
Entering edit mode

Thank you, but I am stuck at writing the function at saving the output from loess and plot. Could you please help me with that?

ADD REPLY

Login before adding your answer.

Traffic: 1432 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6