R: returns the first element and position in each row of the data frame

I have a data frame like this:

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 can i do this?

Thanks.


The solution worked by miracles.

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 cannot determine which index to change.

Thanks.

+5
source share
2 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 
+3
source

Here is another way to do this using data.table

 #Set object as data.table object require(data.table) setDT(DF) 

You can use .SD to cycle .SD each value of each line

 DF[ , .(First=which(!is.na(.SD))[1],Value=c(.SD)[which(!is.na(.SD))[1]]), by=Keyword] # 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 NULL 
0
source

Source: https://habr.com/ru/post/1205723/


All Articles