简体   繁体   中英

Changing value of one column based on condition of another with a loop R

I have a data frame that looks something like this, but it has many paired columns following the format "Name", "F_Name".

    data.frame("Site" = c("X", "Y", "Z"), "Temp" = c(2, 3, 4), "F_Temp" = c(1, 5, -3), "Salinity" = c(5, 6, 7), "F_Salinity" = c(6, 1, -3))

Whenever "F_Name" equals 1 or -3, I want to change the value of "Name" to NA. For example, in the rows where F_Temp equals -3 or 1, I want to change the value of Temp to be NA.

I would like to do this using a loop, as there are many paired columns and I don't want to have to type them all out. What is the best way to go about this?

I would suggest this loop approach as columns are paired:

#Data
df <- data.frame("Site" = c("X", "Y", "Z"),
                 "Temp" = c(2, 3, 4), "F_Temp" = c(1, 5, -3), 
                 "Salinity" = c(5, 6, 7), "F_Salinity" = c(6, 1, -3))
#Detect columns with pattern F_
val <- which(grepl('F_',names(df)))
#Loop
for(i in val)
{
  df[,i-1] <- ifelse(df[,i]==-3 | df[,i]==1, NA, df[,i])
}

Output:

  Site Temp F_Temp Salinity F_Salinity
1    X   NA      1        6          6
2    Y    5      5       NA          1
3    Z   NA     -3       NA         -3

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