Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        3年前关闭。
                                                                                            
                
        
我有一个篮球数据集,其中A列代表不同的球队。是否有一种好的方法可以提取该数据集中的最后几行,例如A列与“勇士”相匹配?

我的意思是我想找到当前行之前的最后3行,其中A列表示“ The Warriors”。我将如何在R(或SQL或Matlab)中执行此操作?

最佳答案

我可以在Matlab中提出解决方案。

首先,为演示起见,让我首先创建一个具有单列A的随机表:

T =

          A
    ______________

    'The Warriors'
    '43'
    '38'
    '40'
    '49'
    '71'
    '69'
    '64'
    '67'
    'The Warriors'
    'The Warriors'
    'The Warriors'
    '131'
    'The Warriors'
    '119'
    '124'
    '93'
    '109'
    '77'
    'The Warriors'
    '83'
    '117'
    '75'
    '122'
    '80'
    'Smith'
    'Johnson'
    'Williams'
    'Jones'
    'Brown'


现在,如果第i行包含字符串true,则可以创建一个在位置i包含'The Warriors'(1)的布尔向量:

matchresult=cellfun(@(x) strcmp(x,'The Warriors'),T.A);


实际上,matchresult现在具有以下形式:

matchresult =

     1
     0
     0
     0
     0
     0
     0
     0
     0
     1
     1
     1
     0
     1
     0
     0
     0
     0
     0
     1
     0
     0
     0
     0
     0
     0
     0
     0
     0
     0


现在,我们可以扫描此向量而不是整个表,以查找最后3行:

for i=4:length(matchresult)                 % since we want 3 rows we can start scanning from the 4th
    if(sum(matchresult(1:i-1))>=3)          % if there are at least 3 ones in previous rows
        fprintf('Scanning row #%d:\n',i);   % see the row index we're scanning
        find(matchresult((1:i-1)),3,'last') % find 1s in previous rows and display last 3 indices
    end
end

08-20 04:25