我有一个篮球数据集,其中 A 列代表不同的球队。有没有一种好方法可以提取该数据集中的最后几行,例如 A 列与“勇士”匹配的行?
我在这里的意思是我想找到当前行之前的最后 3 行,其中 A 列表示“勇士队”。我该如何在 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 行包含字符串 'The Warriors',则可以创建一个 bool 向量,其中在位置
:i
处包含 true
(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
关于mysql - 查找表中与当前行匹配的前一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36740120/