1

I want to write a code that checks two columns in a dataframe and compares them. one is supposed to be the Max Temp and the other is Min Temp. if values of Tmax column is less than the Tmin, then it should interchange the values. I need to do this for multiple files in a folder.

        Date    TMAX    TMIN
1 01/01/1960  4.7353 -4.3722
2 01/02/1960  8.3800 11.0600
3 01/03/1960  3.4400 -3.5300
4 01/04/1960 -1.4300 -8.2200
5 01/05/1960 -1.9600 -5.0100
6 01/06/1960  4.5800 -6.3400
7 01/07/1960 -8.8900 -2.7300

after running the code, it should produce something like

        Date    TMAX    TMIN
1 01/01/1960  4.7353 -4.3722
2 01/02/1960 11.0600  8.3800
3 01/03/1960  3.4400 -3.5300
4 01/04/1960 -1.4300 -8.2200
5 01/05/1960 -1.9600 -5.0100
6 01/06/1960  4.5800 -6.3400
7 01/07/1960 -2.7300 -8.8900
thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • possible duplicate of [How to swap values between 2 columns](http://stackoverflow.com/questions/7746567/how-to-swap-values-between-2-columns) – DatamineR Oct 02 '14 at 21:58

3 Answers3

3
dplyr::mutate(df, TMAX = pmax(TMAX, TMIN), TMIN = pmin(TMAX, TMIN))

Or just

transform(df, TMAX = pmax(TMAX, TMIN), TMIN = pmin(TMAX, TMIN))
Hugh
  • 15,521
  • 12
  • 57
  • 100
2

How about:

df <- data.frame(TMAX=1:5,TMIN=c(2,1,6,3,4))
dfn <- df
dfn$TMAX <- pmax(df$TMIN,df$TMAX)
dfn$TMIN <- pmin(df$TMIN,df$TMAX)
##   TMAX TMIN
## 1    2    1
## 2    2    1
## 3    6    3
## 4    4    3
## 5    5    4
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • Thank You for your help, however this adds two more columns to my dataframe. I just need the same format as my original data – user3386398 Oct 03 '14 at 02:17
  • really? can you give a reproducible example that shows that? (Maybe the capitalization is different in your real data set?) – Ben Bolker Oct 03 '14 at 12:02
1

(Maybe not the most elegant way) Assuming your data is called df:

check<-df[,2]>df[,3]

dfn<-df
dfn[!check,3]<-df[!check,2]
dfn[!check,2]<-df[!check,3]

And a more elegant way is:

transform(df, V2=ifelse(V2<V3,V3,V2),V3= ifelse(V3>V2,V2,V3))
DatamineR
  • 10,428
  • 3
  • 25
  • 45