Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Return the First Element and Position in Each Row of a Data Frame

Tags:

r

na

I have a data frame like so:

Keyword   1    2    3    4    5
a        0.7  NA   NA   0.3  0.4
b         NA  NA   0.5   NA   NA
c         NA 0.2   NA    NA  0.3
d         NA  NA   NA   0.3  0.4

I would like to get it so that the results give me this:

Keyword  First   Value
a          1      0.7 
b          3      0.5
c          2      0.2
d          4      0.3

How would I go about doing so?

Thanks.


The solution worked wonders.

What if I want the last value so that the result looks like this:

Keyword  Last    Value
a          5      0.4
b          3      0.5
c          5      0.3
d          5      0.4

I can't tell which index to change.

Thanks.

like image 712
Cinji18 Avatar asked Oct 19 '22 23:10

Cinji18


1 Answers

DF <- read.table(text="Keyword   1    2    3    4    5
a        0.7  NA   NA   0.3  0.4
b         NA  NA   0.5   NA   NA
c         NA 0.2   NA    NA  0.3
d         NA  NA   NA   0.3  0.4
e         NA  NA   NA   NA   NA", header=TRUE)

setNames(
  data.frame(DF[,1],
             t(apply(DF[-1], 1, function(x) {
               ind <- which(!is.na((x)))[1]
               c(ind, x[ind])
             }))
  ), c("Keyword",  "First",   "Value"))
#  Keyword First Value
#1       a     1   0.7
#2       b     3   0.5
#3       c     2   0.2
#4       d     4   0.3
#5       e    NA    NA
like image 179
Roland Avatar answered Oct 23 '22 03:10

Roland