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)
manpreet
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 adata.frame
inR
as so: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:
In practice the data I will be using will have
n
columns andn
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.