R: Finding the middle row of a column and returning a value

General Tech Learning Aids/Tools 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Learning Aids/Tools related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

I am new to R, stackOverflow, and codding in general (hands on learning) so forgive me if I make any mistakes. I have a data.frame in R as so:

Year Location A  Location B   Location C 
1900    NA          1             NA
1901    NA          3             5
1902    3           NA            6
1903    4           NA            4
1902    6           NA            NA

I've tried all sorts of approaches with no success, what I need is to identify the middle row in each location column and return the corresponding value from the Year column, for example:

Location A   Location B  Location C
    1903          1901        1902

In practice the data I will be using will have n columns and n rows. The aim of extracting this data is to aid in produce a graphical output with the name of each location centered over the graphical line output.

profilepic.png
manpreet 2 years ago

You could try the following:

idx <- apply(df,2,function(x)(min(which(!is.na(x))))+floor(length(na.omit(x))/2))[-1]
df2 <- rbind(colnames(df)[-1],df[idx,1])
#> df2
#     [,1]         [,2]         [,3]        
#[1,] "Location.A" "Location.B" "Location.C"
#[2,] "1903"       "1901"       "1902"      

The first part of the apply() function is essentially a wrapper for a loop over all columns of the dataframe df. The number 2, as the second parameter, is the so-called margin. It indicates that columns are selected (and not rows, which would be chosen by using the margin 1).

What follows is a function that calculates the relevant row number for each column. The part min(which(!is.na(x)))) yields the index of the first element in the column (counting from the top) that is not NA. Here x is a vector containing the column of df that is selected by apply(). Then the length of the sequence of non-NA entries is calculated with length(na.omit(x)). This length is divided by two, to obtain the "middle" of the sequence. The function floor() ensures that the value is rounded to the next-lowest integer if the result is not an integer. The output of apply() is a vector idx containing the row index for each column of interest. With the [-1] at the end of the line we discard the result for the first column, "Year", which is not important here.

As an example, in "Location C" (column four) we have min(which(!is.na(df[,4]))) equal to 2. We add to this number floor(length(na.omit(df[,4]))/2), which is equal to floor(1.5) and results in 1. Thus, the value of idx of column 4 is 2+1=3.

The second line of the code assembles the resulting matrix df2 by using the names of the columns of the original dataframe and the entry of the "Year" (column 1) according to the previously calculated row index idx for each column of df.

Hope this helps.

data

text <-"Year 'Location A'  'Location B'   'Location C' 
     1900    NA          1             NA
     1901    NA          3             5
     1902    3           NA            6
     1903    4           NA            4
     1902    6           NA            NA"
df <- read.table(text=text, header=T)

0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

tuteehub community

Join Our Community Today

Ready to take your education and career to the next level? Register today and join our growing community of learners and professionals.

tuteehub community