0

I have a dataframe with lots of columns, including four that represents sub-categories.

data.frame(site_name=c("bla","blo","blu"), page_1=c(NA,NA,NA), page_2=c(NA,"detail_1","detail_2"), page_3=c("hello", "hola", NA), page_4=c(NA,NA,NA)) 

  site_name page_1   page_2 page_3 page_4
1       bla     NA     <NA>  hello     NA
2       blo     NA detail_1   hola     NA
3       blu     NA detail_2   <NA>     NA

I would like to replace all these 'page_x' columns with one single column, showing only the right-most non-NA level of detail. There are lots of row-wise questions, but I cannot find one working with NSE and Reduce.

In the example above that would be:

  site_name page_1   page_2 page_3 page_4     page
1       bla     NA     <NA>  hello     NA    hello
2       blo     NA detail_1   hola     NA     hola
3       blu     NA detail_2   <NA>     NA detail_2

I thought it would be a good example to use Reduce over each row. I have a version that kind of work on one single row, but I cannot find a way to apply it to mutate_.

Reduce(function(prec,col){ifelse(!is.na(row[col]), row[col], prec)},
       grep("^page",names(row),value=T), NA)}

This does not work (as I guess the 'row' object is not really passed this way):

mutate_(.dots = ~Reduce(function(prec,col){ifelse(!is.na(row[col]), row[col], prec)},
       grep("^page",names(row),value=T), NA)}
xav
  • 4,101
  • 5
  • 26
  • 32

1 Answers1

0

Here is a different idea without Reduce,

apply(df[2:ncol(df)], 1, function(i) tail(i[!is.na(i)], 1))
#[1] "hello"    "hola"     "detail_2"
Sotos
  • 51,121
  • 6
  • 32
  • 66