简体   繁体   中英

If value in one column is greater than the value of another then interchange the values in the columns in R

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
dplyr::mutate(df, TMAX = pmax(TMAX, TMIN), TMIN = pmin(TMAX, TMIN))

要不就

transform(df, TMAX = pmax(TMAX, TMIN), TMIN = pmin(TMAX, TMIN))

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM