在R中,如何根据列值的某些条件计算数据帧的行数?

时间:2015-01-20 17:45:13

标签: r count row

cylinders   displacement    horsepower  weight  acceleration    model   origin  class
1   8   307.0   130 3504    12.0    70  1   18.0
2   8   350.0   165 3693    11.5    70  1   15.0
3   8   318.0   150 3436    11.0    70  1   18.0
4   8   304.0   150 3433    12.0    70  1   16.0
5   8   302.0   140 3449    10.5    70  1   17.0
6   8   429.0   198 4341    10.0    70  1   15.0
7   8   454.0   220 4354    9.0 70  1   14.0
8   8   440.0   215 4312    8.5 70  1   14.0
9   8   455.0   225 4425    10.0    70  1   14.0
10  8   390.0   190 3850    8.5 70  1   15.0
11  8   383.0   170 3563    10.0    70  1   15.0
12  8   340.0   160 3609    8.0 70  1   14.0
13  8   400.0   150 3761    9.5 70  1   15.0
14  8   455.0   225 3086    10.0    70  1   14.0
15  4   113.0   95  2372    15.0    70  3   24.0
16  6   198.0   95  2833    15.5    70  1   22.0
17  6   199.0   97  2774    15.5    70  1   18.0
18  6   200.0   85  2587    16.0    70  1   21.0
19  4   97.0    88  2130    14.5    70  3   27.0
20  4   97.0    46  1835    20.5    70  2   26.0
21  4   110.0   87  2672    17.5    70  2   25.0
22  4   107.0   90  2430    14.5    70  2   24.0
23  4   104.0   95  2375    17.5    70  2   25.0

假设上面是我的数据框,我如何计算其原点为2的行号?即应该是4

1 个答案:

答案 0 :(得分:2)

nrow(df[df$origin == 2,]) 
# or slightly quicker
length(df[df$origin == 2, 1]) # subset will be marginally quicker

或者@akrun就在上面。