【发布时间】:2019-10-02 22:01:34
【问题描述】:
我有一个包含两列文本和颜色的数据框。
library(tidyverse)
library(purrr)
# sample dataframe
df <- data.frame(Text = c("text1", "text2", "text3", "text4"),
Colours = c("blue", "white", "green", "yellow"), stringsAsFactors = F)
我需要的是一个数据框,比如说,NOT_Blue,它包括除包含“蓝色”的行之外的所有行。换句话说,一个具有所有颜色的数据框,除了那些不等于“蓝色”的颜色。最后我想把这些数据帧写成 csv 文件。
对于一个使用dplyr::filter 和!=(不相等)的数据框会起作用
not_blue <- df %>% filter(!Colours == "blue")
not_blue
Text Colours
1 text2 white
2 text3 green
3 text4 yellow
问题是我需要为每种颜色/类别创建不同的数据框。
我想我需要使用其中一个 apply/map 系列函数。所以我创建了一个带有颜色的矢量,希望在函数中使用它。
# colours to feed the function
colours <- c("blue", "white", "green", "yellow")
# trying to make a function
remaining_colours <- function(x) {
df <- df %>% filter(!Colours == x)
}
# using the formula with map_df of purrr
map_df(colours, remaining_colours) %>% arrange(Text)
# epic fail results
Text Colours
1 text1 blue
2 text1 blue
3 text1 blue
4 text2 white
5 text2 white
6 text2 white
7 text3 green
8 text3 green
9 text3 green
10 text4 yellow
11 text4 yellow
12 text4 yellow
您能帮我或说明如何为这种情况制作应用/映射/循环吗?
提前致谢!
【问题讨论】:
标签: r function dataframe filter lapply