Y. Lin
Y. Lin

Reputation: 99

Select a subset of a dataframe

I have a large dataframe, so I want to create a small subset of the dataframe to test my function.

 a=seq(from=1, to =1000, by=10)
 b=seq(from=1,to=20000, by=100)
 small_df <- df [a,b]

And samll_df end up be a vector containing the numbers in b .

What is the right way to do it?

expect output:

       col1  col11 col21 ........col91
   row1
   row11
   row21
   row31
    ...
   row19901 

Upvotes: 0

Views: 121

Answers (1)

narendra-choudhary
narendra-choudhary

Reputation: 4826

The method you're using works fine for a data frame. Here is an example.

df <- data.frame(a = 1:10, b = 11:20, c = 21:30, d = 51:60)

 #     a  b  c  d
 #1    1 11 21 51
 #2    2 12 22 52
 #3    3 13 23 53
 #4    4 14 24 54
 #5    5 15 25 55
 #6    6 16 26 56
 #7    7 17 27 57
 #8    8 18 28 58
 #9    9 19 29 59
 #10  10 20 30 60

# Extracting rows and columns
df[c(1,3,5,7,9),c(1,3)]

#      a  c
#1     1 21
#3     3 23
#5     5 25
#7     7 27
#9     9 29

This method won't work for a data table. The rules for subsetting are different for a data table.

Upvotes: 2

Related Questions