Operation for element in dataframe

Hi, community.

I meet an basic but interesting question when practicing R. How could we do the same operation on each element of the data frame, for example every element + 1? I know c5+1 or sapply function work. Is there any way?

What's more, how could we do different operation for element in different column or row? For example, first column(or row)+1, others not change. Or the element in odd number column(or row)+1, others-10.

Any help would be appreciated.

 c1<-c(16.6,1.0,10.1,NA,8.0,17.0,2.4,7.6,5.7,11.6,3.6,2.8,6.3,1.5,2.7,16.7,6.7,5.3,12.5)
 c2<-c(13.0,11.2,11.0,15.0,10.0,11.5,NA,7.8,9.2,6.6,1.6,8.2,18.0,18.9,7,9,2.9,16.1,17.8)
 c3<-c(4.2,5.6,1.4,3.4,5.0,5.8,5.1,8.2,8.8,9.1,1.9,7.7,9.1,10.6,3.7,9.9,10.2,11.5,5)
 c4<-c(9,8,1.4,0.2,5.0,5.8,3,8.2,1.2,9.1,1.9,25,9.1,3.6,3.7,11,10.2,33,5)
 c5<-data.frame(c1,c2,c3,c4)
 colnames(c5)<-c("col1","col2","col3","col4")

Maybe something like this for the alternating row issue?

xx  <- seq(1, 19, by = 2)
c5[xx, 1 ]  <- c5[xx, 1] + 1
1 Like

@jrkrideau
Thank you for your help.
Would you mind to show your opinion more specifically according to original post question?

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.