TextとColoursの2つの列を持つデータフレームがあります。
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
and !=
(等しくない)を使用する1つのデータフレームでは機能します
not_blue <- df %>% filter(!Colours == "blue")
not_blue
Text Colours
1 text2 white
2 text3 green
3 text4 yellow
重要なのは、色/カテゴリごとに異なるデータフレームを作成する必要があるということです。
apply / mapファミリー関数の1つを使用する必要があると思います。そこで、関数で使用することを期待して、色を使用してベクトルを作成します。
# 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
この場合の適用/マップ/ループの作成方法を教えてください。
前もって感謝します!
を使用する方法は次のとおりlapply
です。これにより、必要なデータフレームのリストが作成されます。
colours <- c("blue", "white", "green", "yellow")
result <- lapply(colours, function(x) {
df %>% filter(!Colours == x)
}) %>%
setNames(paste0("NOT_", colours))
result
$NOT_blue
Text Colours
1 text2 white
2 text3 green
3 text4 yellow
$NOT_white
Text Colours
1 text1 blue
2 text3 green
3 text4 yellow
$NOT_green
Text Colours
1 text1 blue
2 text2 white
3 text4 yellow
$NOT_yellow
Text Colours
1 text1 blue
2 text2 white
3 text3 green
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加