r - How to select row's last values in a data frame and arrange them in a separate column? -


i have data frame of following type:

enter image description here

i need create separate column include last variables each row starting column v9, i.e. 15:32, 13:44, 16:37, 15:31, null, null, 16:10, 16:22 etc. if easier, can live removing empty rows (in case 5 , 6). tried combination of which.max, length , apply, output did not make sense. have no idea next. help.

we use max.col. subset columns 'v9' 'v11'. then, use max.col column index of elements not blank. in case of 'ties', there optional argument in 'max.col' i.e. ties.method specify either 'first', 'last' or 'random'. default option 'random'. here, using 'last' option. cbind sequence of 'row' create 'row/column' index , extract values 'dfn'.

dfn <- df1[paste0('v', 9:11)] new <- dfn[cbind(1:nrow(dfn),max.col(dfn!='', 'last'))] new   #[1] "15:32" "13:44" "16:37" "15:31" ""      ""      "16:10" "16:22" "16:21" #[10] "15:34" "16:26"  cbind(dfn, new) #     v9   v10   v11   new #1  15:32             15:32 #2        13:44       13:44 #3  16:37             16:37 #4  15:31             15:31 #5                          #6                          #7  12:07 12:32 16:10 16:10 #8  12:09 12:36 16:22 16:22 #9  12:06 12:35 16:21 16:21 #10 12:08 12:26 15:34 15:34 #11 12:35 13:00 16:26 16:26 

or can use apply

apply(dfn, 1, function(x) if(any(x!='')) tail(x[x!=''],1) else '') #[1] "15:32" "13:44" "16:37" "15:31" ""      ""      "16:10" "16:22" "16:21" #[10] "15:34" "16:26" 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -