-1

enter image description here

enter image description here

Currently analysing climate data and need to find the year (rows) where net-zero emissions are reached for each model (columns).

I did a loop to extract the value of the first instance of a negative value i.e. negative emissions for each model (shown in photo, nz_temp row).

I need to now create a row which has the year of this instance.

Any help would be appreciated.

I tried to use the pull function but got completely stuck!

Phil
  • 7,287
  • 3
  • 36
  • 66
  • 1
    Please do not post pictures. If you follow [this](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610) guide you're guaranteed to get high quality answers quickly. – Andre Wildberg Jun 18 '23 at 16:33

1 Answers1

0

Don't think of R like a spreadsheet program. It's important to think column-wise when you use R. There is almost never a need to create a new row for anything that contains an "answer".

What I would suggest is to create a set of columns that contain True/False values for negative numbers. Then use subscripting on them.

Here is a tiny example, step by step:

> dput(my.data)
structure(list(Year = c(2000, 2001, 2002), V1 = c(3, -4, -10), 
    V2 = c(-500, -1000, -1200), V3 = c(1, 2, -3)), class = "data.frame", row.names = c(NA, 
-3L))

#> my.data
#  Year  V1    V2 V3
#  2000   3  -500  1
#  2001  -4 -1000  2
#  2002 -10 -1200 -3

# are any values in V1, V2, or V3 less than 0?
my.data$V1.neg.TF <- my.data$V1.neg.TF[my.data$V1.neg.TF][1] < 0 
my.data$V2.neg.TF <- my.data$V2.neg.TF[my.data$V2.neg.TF][1] < 0
my.data$V3.neg.TF <- my.data$V3.neg.TF[my.data$V3.neg.TF][1] < 0

#> my.data
#  Year  V1    V2 V3 V1.neg.TF V2.neg.TF V3.neg.TF
#1 2000   3  -500  1     FALSE      TRUE     FALSE
#2 2001  -4 -1000  2      TRUE      TRUE     FALSE
#3 2002 -10 -1200 -3      TRUE      TRUE      TRUE

Notice how the True/False values indicate where the negative values appear first.

Now we use subscripting:

my.data$Year[my.data$V1.neg.TF][1]

this says to grab the sequence of Year (my.data$Year) where there is a negative (my.data$V1.neg.TF) and then return the first element of that vector ([1]).

So you could do

c(
my.data$Year[my.data$V1.neg.TF][1], 
my.data$Year[my.data$V2.neg.TF][1], 
my.data$Year[my.data$V3.neg.TF][1]
)

which would give you 2001 2000 2002, which is what I think you want.

David
  • 572
  • 3
  • 12
  • That's really useful thank you. It worked when I did: for(i in 2:ncol(c1_flip)){neg.TF <- c1_flip[i]<0 c1_flip <- cbind(c1_flip, neg.TF)} – Holly Wakelin Jun 19 '23 at 10:06