基于R中的简单VLOOKUP创建数据框?

时间:2018-04-02 18:20:12

标签: r

df <- iris
x <- data.frame(Petal.Length=c('1.7', '1.9', '3.5'))

对于所有具有“x”中指定的花瓣长度的行,新数据框(dfnew)需要提取“虹膜”中的所有5列。

我已经尝试过这种方式,但它似乎不起作用:

dfnew <- df$Petal.Length[x]

2 个答案:

答案 0 :(得分:2)

使用dplyr

> library(dplyr)
> data(iris)
> (dfnew <- iris %>% filter(Petal.Length %in% c('1.7', '1.9', '3.5')) )
  Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1          5.4         3.9          1.7         0.4     setosa
2          5.7         3.8          1.7         0.3     setosa
3          5.4         3.4          1.7         0.2     setosa
4          5.1         3.3          1.7         0.5     setosa
5          4.8         3.4          1.9         0.2     setosa
6          5.1         3.8          1.9         0.4     setosa
7          5.0         2.0          3.5         1.0 versicolor
8          5.7         2.6          3.5         1.0 versicolor

答案 1 :(得分:1)

值得注意的是,这是你在技术上要求的“VLOOKUP”,但是phiver的评论可能实际上就是你想要的。

df <- iris
x <- data.frame(Petal.Length=c('1.7', '1.9', '3.5'), X = c('X','Y','Z'))

df.new <- merge(df, x, by = 'Petal.Length')