简体   繁体   中英

Remove elements in a vector that are greater than value

I need to remove elements (that I am plotting with error bars, so I need to remove that data point from all four vectors below) where the diff vector is greater than 2*std. Here was my thought:

for (i in 1:length(Z)){
  if (diff[[i]]>=(2*std)){
    Z[[i]] <- NULL
    ucl[[i]] <- NULL
    lcl[[i]] <- NULL
    x[[i]] <- NULL
    }
} 

The for loop stops completely after it enters the if statement for the first time. I have learned R completely on my own, so please respond to me as if I know next to nothing.

Don't use a for loop. Do something like this if you want to replace certain values by NA:

Z[diff >= 2*std] = NA

Alternatively, if you want to just filter out the rows that don't satisfy the condition, subset only the rows you want:

Z <- Z[diff < 2*std]

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