在R中,如何根据列值的特定条件来计算数据帧的行数?

时间:2021-08-14 13:36:05
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

Suppose above is my data frame, how would I count the row number whose origin is 2? i.e. and should be 4

假设上面是我的数据帧,我如何计算原点为2的行号?也就是4。

1 个解决方案

#1


2  

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

Or as @akrun has above.

或者如@akrun所述。

#1


2  

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

Or as @akrun has above.

或者如@akrun所述。