dplyr - 将colum值作为字符向量

时间:2018-04-02 10:31:34

标签: r dplyr

提供如下数据框,

text <- "
CAR_MODEL,ENGINE_VENDOR,var,value,label
Toyota Corolla,FIAT,Three_Family_Pct,33.98,33.98
Nissan Sunny,PRATNEY,Three_Family_Pct,29.84,29.84
Renault Duster,FIAT,Three_Family_Pct,27.86,27.86
Suzuki Ciaz,FIAT,Three_Family_Pct,26.6,26.6
Renault Duster,FIAT,Single_Family_Pct,0,0
Toyota Corolla,FIAT,Single_Family_Pct,0,0
Nissan Sunny,PRATNEY,Single_Family_Pct,0,0
Suzuki Ciaz,FIAT,Single_Family_Pct,0,0
Suzuki Ciaz,FIAT,Two_Family_Pct,42.37,42.37
Renault Duster,FIAT,Two_Family_Pct,41.53,41.53
Toyota Corolla,FIAT,Two_Family_Pct,36.31,36.31
Nissan Sunny,PRATNEY,Two_Family_Pct,32.27,32.27
Nissan Sunny,PRATNEY,Four_Family_Pct,37.89,37.89
Suzuki Ciaz,FIAT,Four_Family_Pct,31.03,31.03
Renault Duster,FIAT,Four_Family_Pct,30.61,30.61
Toyota Corolla,FIAT,Four_Family_Pct,29.71,29.71
Nissan Sunny,PRATNEY,Mileage,12688.5,12688
Suzuki Ciaz,FIAT,Mileage,11989,11989
Renault Duster,FIAT,Mileage,11132.5,11132
Toyota Corolla,FIAT,Mileage,10357,10357
"
df <- read.table(textConnection(text), sep=",", header = T)

我使用以下操作获取CAR_MODEL名称

df %>% filter(var == 'Mileage') %>% arrange(desc(value))

这给了我一个如下数据框。

       CAR_MODEL ENGINE_VENDOR     var   value label
1   Nissan Sunny       PRATNEY Mileage 12688.5 12688
2    Suzuki Ciaz          FIAT Mileage 11989.0 11989
3 Renault Duster          FIAT Mileage 11132.5 11132
4 Toyota Corolla          FIAT Mileage 10357.0 10357

在链式命令中将dplyr提取为字符向量的CAR_MODEL方法是什么?

df %>% filter(var == 'Mileage') %>% arrange(desc(value)) %>% "What should go here ? "

我理解使用select来选择特定的列,但是返回的数据帧不是所需的字符向量。

1 个答案:

答案 0 :(得分:1)

这应该有用。

 as.character(df %>% filter(var == 'Mileage') %>% arrange(desc(value)) %>% pull(CAR_MODEL))

<强>结果

[1] "Nissan Sunny"   "Suzuki Ciaz"    "Renault Duster" "Toyota Corolla"