我正在使用一个包含来自不同国家的观察结果的数据框。我只想选择我确定的列表中的国家。
Country.Name Country.Code Indicator.Name Indicator.Code year fert
1 Aruba ABW Fertility rate, total (births per woman) SP.DYN.TFRT.IN X1960 4.820000
2 Afghanistan AFG Fertility rate, total (births per woman) SP.DYN.TFRT.IN X1960 7.450000
3 Angola AGO Fertility rate, total (births per woman) SP.DYN.TFRT.IN X1960 7.478000
4 Albania ALB Fertility rate, total (births per woman) SP.DYN.TFRT.IN X1960 6.489000
5 Andorra AND Fertility rate, total (births per woman) SP.DYN.TFRT.IN X1960 NA
6 Arab World ARB Fertility rate, total (births per woman) SP.DYN.TFRT.IN X1960 6.948747
.....
例如,我只需要列表c('Aruba','Albania''Germany')
我已经尝试过了,但是由于某种原因它不起作用。
d_f <- read.csv('fertility_rate.csv') %>%
gather(year, fertility, X1960:X2017)
d_fer <- d_f[d_f$Country.Name %in% selected_countries,]
这是详细的代码:
pupil_ratio <- read.csv('pupil_ratio.csv') #this data has all the countries I want
countries <-as.vector(pupil_ratio$Country.Name) #I convert it to a vector
d_f <- read.csv('fertility_rate.csv') %>%
gather(year, fert, X1960:X2017)
d_fer <- d_f[d_f$Country.Name %in% countries,]
答案 0 :(得分:2)
您好,只需按如下所示进行索引
d_fer <- d_f[(d_f$Country.Name %in% c('Aruba', 'Albania' 'Germany')),]
或
dataframe[c('Aruba', 'Albania' 'Germany'),]
希望它能工作。
答案 1 :(得分:1)
dplyr::filter()
应该可以正常工作:
d_f <- read.csv('fertility_rate.csv') %>%
gather(year, fert, X1960:X2017) %>%
dplyr::filter(Country.Name %in% countries) # only select countries which are in countries