简体   繁体   中英

R - dplyr select() & filter()

I'm a relatively new user of R and am trying to filter out relevant variables as well as ignoring NA s in order to make some graphics. As I use the select() function I get following error message:

no applicable method for 'select_' applied to an object of class "c('integer', 'numeric')"

The code I'm using is this:

select(year, Total_US_received, Total_US_required)

What am doing wrong?

You need to use pipe operator - %>% to "push" your input data frame into select handler function of 'dlyr` package. Please see the simulation code below:

library(dplyr)

# data simulation
set.seed(123)
df <- data.frame(
  year = 2011:2018, 
  Total_US_received = (1:8) * 100, 
  Total_US_required = (1:8) * 50,
  no_need1 = rnorm(8),
  no_need2 = rnorm(8)
)

head(df)
#  year Total_US_received Total_US_required    no_need1   no_need2
# 1 2011               100                50 -0.56047565 -0.6868529
# 2 2012               200               100 -0.23017749 -0.4456620
# 3 2013               300               150  1.55870831  1.2240818
# 4 2014               400               200  0.07050839  0.3598138
# 5 2015               500               250  0.12928774  0.4007715
# 6 2016               600               300  1.71506499  0.1106827


# this is how select works in dplyr
df_out <- df %>% select(year, Total_US_received, Total_US_required)
head(df_out)

Output:

  year Total_US_received Total_US_required
1 2011               100                50
2 2012               200               100
3 2013               300               150
4 2014               400               200
5 2015               500               250
6 2016               600               300

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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