Operation of dataframe column in R

Hi, community! Long time no see. I meet another interesting question when practicing R.
As you see, dataframe c5 is here. How could I let value in col4 subtract value in col3. Like in first row, 9-4.2=4.8, then value in c5[1,3] is 4.8. And then 4.8-13.0=-8.2, then c5[1,2]=-8.2. The same -8.2-16.6=-24.8, c5[1,1]=-24.8. Other rows operation is almost same. But I try the diff() in R, hysteresis difference is not the same with this question. Maybe a loop or other function in R?

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")

If I understand what you want, this will do it and add the resulting vector to your data.frame

c5$sub <- c5$col4 - c5$col3
1 Like

@jrkrideau Thank you! It helped me. it's my problem. I don't make it clear more. As you could see, we want c5$col3<-c5$col4-c5$col3. And then new col3-col2 as col2 value, it's c5$col2<-c5$col3-c5$col2, and then c5$col1<-c5$col2-c5$col1. So,if there are many colmuns, how could we loop it or use a function? Just use it as an example.

Here are two ways to iterate over the columns with a loop.

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")

#Using column positions
for(i in 3:1) {
  c5[i] <- c5[i+1] - c5[i]
}


#Using names
for(i in 3:1) {
  LowerCol <- paste0("col", i)
  UpperCol <- paste0("col", i + 1)
  c5[LowerCol] <- c5[UpperCol] - c5[LowerCol]
}

Created on 2024-02-27 with reprex v2.0.2

1 Like

This topic was automatically closed 7 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.