Reputation: 2412
I have a data frame that has 500 rows and at least a dozen columns per row. Some rows have a lot more columns. What I want to do is to create a variable that contains the contents of the last filled cell, per row.
dput(head(calls_with_overlap, 10))
A B C D
1. aknasd kasdknsd kasdkas kasdpa
2. asdhad none
3. apihsd piahsdas ashpidapishd phasd askdn wads
4. kasdas none
What I tried so far is:
if (calls_with_overlap$Overlap[10] = "none")
{
Ending <- TRUE
}
else (Ending <- FALSE)
if (Ending == FALSE)
{
for (q in 1:1024) #max is 1024 columns. perhaps not best way for number of columns.
{
EndingCell <- c(10 + q)
EndingCellcontents <- calls_with_overlap[h,EndingCell] # h is from an outer loop, going through each row.
if (EndingCellcontents != ""){
EndingCellcontents[q] <- EndingCellcontents}
last <- length(EndingCellcontents)
last<- EndingCellcontents[last]
}}
I would like "last" to contain the last filled cell in each row, unless it says "none". Starting from column B.
i.e. in this case
last
[1] kasdpa
[2] wads
Apologies if this is a nooby question, but I'm teaching myself programming from scratch.
Upvotes: 3
Views: 317
Reputation: 48211
Edited: mistaken rows and columns
df <- data.frame(A=c("r","","z"),B=c("w","",""))
df
A B
1 r w
2
3 z
v <- apply(df, 1, function(x) x[rev(which((x!="")==TRUE))[1]])
[1] "w" NA "z"
v[!is.na(v)]
[1] "w" "z"
Upvotes: 4