简体   繁体   中英

Print elements of vector in single line

I have a dataframe with 12 rows and two columns one with dates and the other with temperatures. I want to extract the values that meet the criteria in my if-statement (temperature is smaller than or equal to -20). This is my code:

for (row in 1:12) {
  T <- winter[row, 2]
  
  if(T <= -20) {
    x <-c(winter[row,2])
    print(x)
  }
}

Print x gives me this:

[1] -27
[1] -21
[1] -24
[1] -34
[1] -20

But I want something like this:

[1] -27, -21, -24, -34, -20

Dput:

dput(winter)
structure(list(date = 1:12, temp = c(-27L, -21L, -8L, -12L, 
-10L, -24L, 8L, -7L, -34L, -19L, -2L, -20L)), class = "data.frame", row.names = c(NA, 
-12L))

Make use of vectorized conditional indexing (basically just figure out which rows you want):

mask <- winter[1:12, 2] <= -20

winter[mask, "temp"]
# [1] -27 -21 -24 -34 -20

This is sometimes referred to as a "boolean mask", although that's a more common term in Python. You can read up on this indexing method in R in section 4.5.7 of Hadley's "Advanced R" book, here .

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