R-在不知道行号的情况下键入data.frame中的数据

时间:2019-12-26 09:28:09

标签: r dataframe

如果有一个数据框名称为“ DF”,那么在不知道行号的情况下如何输入“黄色”。

来自

     fruit  year  color
?    apple  2017  red
?    apple  2018  red
?    apple  2019  red
?    banana 2017 
?    banana 2018
?    banana 2019
?    orange 2017  orange
?    orange 2018  orange
?    orange 2019  orange

     fruit  year  color
?    apple  2017  red
?    apple  2018  red
?    apple  2019  red
?    banana 2017  yellow
?    banana 2018  yellow
?    banana 2019  yellow
?    orange 2017  orange
?    orange 2018  orange
?    orange 2019  orange

1 个答案:

答案 0 :(得分:0)

一种方法是创建一个查询数据框,然后基于matchfruit

color_fruit <- data.frame(fruit = c('apple', 'banana', 'orange'), 
              color = c('red', 'yellow', 'orange'), stringsAsFactors = FALSE)

df$color <- color_fruit$color[match(df$fruit, color_fruit$fruit)]
df

#   fruit year  color
#1  apple 2017    red
#2  apple 2018    red
#3  apple 2019    red
#4 banana 2017 yellow
#5 banana 2018 yellow
#6 banana 2019 yellow
#7 orange 2017 orange
#8 orange 2018 orange
#9 orange 2019 orange

或者我们也可以加入

merge(df, color_fruit, by = 'fruit')[-3]

数据

df <- structure(list(fruit = c("apple", "apple", "apple", "banana", 
"banana", "banana", "orange", "orange", "orange"), year = c(2017L, 
2018L, 2019L, 2017L, 2018L, 2019L, 2017L, 2018L, 2019L), color = c("red", 
"red", "red", "", "", "", "orange", "orange", "orange")), class = "data.frame", 
row.names = c(NA, -9L))