Tushar Lad
Tushar Lad

Reputation: 484

How to subset the data frame based on selected variable with limited column?

i would like to subset limited column and selected variable as i have multiple column in my data frame.

my sample data:

df <- data.frame('ID'=c('A','B','C'),'YEAR'=c('2020','2020','2020'),'MONTH'=c('1','1','1'),'DAY'=c('16','16','16'),'HOUR'=c('15','15','15'),'VALUE1'=c(1,2,3))

i would like to subset ID'='C' and column name 'VALUE1' Expected output:-

  ID VALUE1
1  C      3

Appreciate any help...!

What i have tried so far is.

df1 <- subset(df,df$ID=='C')
df2 <- subset(df1,select=c('ID','VALUE1')

Is there any efficient way to do that as creating multiple data frame when we have multiple is not good.

Upvotes: 3

Views: 124

Answers (2)

Prahlad
Prahlad

Reputation: 138

you can use dplyr chaining function too,

df %>% select(ID,VALUE1) %>% filter(ID=="C")

Upvotes: 2

akrun
akrun

Reputation: 887741

We can have both subset and select

subset(df, subset = ID=='C', select = c('ID', 'VALUE1'))

Upvotes: 2

Related Questions