简体   繁体   English

R按条件行号选择多行

[英]R select multiple rows by conditional row number

I have a R dataframe like this one: 我有一个像这样的R数据帧:

a<-c(1,2,3,4,5)
b<-c(6,7,8,9,10)
df<-data.frame(a,b)
colnames(df)<-c("a","b")

df
  a  b
1 1  6
2 2  7
3 3  8
4 4  9
5 5 10

I would like to get the 1st, 2nd, 3rd AND 5th row of the column a , so 1 2 3 5 , by selecting rows by their number. 我希望通过按行号选择行来获得列a第1行,第2行,第3行和第5行,即1 2 3 5

I have tried df$a[1:3,5] but I get Error in df$a[1:3, 5] : incorrect number of dimensions . 我试过df$a[1:3,5]但我Error in df$a[1:3, 5] : incorrect number of dimensions df$a[1:3,5]得到Error in df$a[1:3, 5] : incorrect number of dimensions What DOES work is c(df$a[1:3],df$a[5]) but I was wondering if there was an easier way to achieve this with R? 什么工作是c(df$a[1:3],df$a[5])但我想知道是否有更简单的方法来实现这个与R?

Your data frame has two dimensions (rows and columns). 您的数据框有两个维度(行和列)。 When you use the square brackets to extract values, R expects everything prior to the comma to indicate the rows desired, and everything after the comma to indicate the columns desired (see: ?[ ). 当您使用方括号来提取值时,R期望逗号之前的所有内容指示所需的行,并且逗号之后的所有内容都指示所需的列(请参阅: ?[ )。 Hence, df[1:3,5] means rows 1 through 3, from column 5. To turn your desired rows into a single vector, you need to concatenate (ie, c(1:3,5) ). 因此, df[1:3,5]表示第5行的第1行到第3行。要将所需的行转换为单个向量,需要连接(即c(1:3,5) )。 That would all go before the comma, the column indicator, 1 or "a" , would go after the comma. 这将全部发生在逗号之前,列指示符1"a"将在逗号之后。 Thus, df[c(1:3,5), 1] is what you need. 因此, df[c(1:3,5), 1]就是你所需要的。


For alternative answer (that might be more appropriate to a dataframe with many more columns), df[c(1:3, 5), "a"] as suggested by @Mamoun Benghezal would also get it done! 对于替代答案(可能更适合具有更多列的数据帧),@ Mamoun Benghezal建议的df[c(1:3, 5), "a"]也可以完成它!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM