3

我有一个数据框,它有 500 行,每行至少有十几列。有些行有更多的列。我想要做的是创建一个变量,其中包含每行最后一个填充单元格的内容。

输入(头部(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

到目前为止我尝试的是:

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]
      }}

我希望“最后一个”包含每行中最后一个填充的单元格,除非它说“无”。从 B 列开始。

即在这种情况下

last
[1] kasdpa
[2] wads

如果这是一个令人讨厌的问题,我深表歉意,但我正在从头开始自学编程。

4

1 回答 1

4

编辑:错误的行和列

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"
于 2012-06-29T14:01:32.567 回答