[英]Mutate, case_when, paste in R
蘋果 | 香蕉 | 橙 | 水果名稱 |
---|---|---|---|
1 | 0 | 1 | 蘋果橙 |
1 | 0 | 0 | 蘋果 |
1 | 0 | 1 | 蘋果橙 |
1 | 1 | 1 | 蘋果香蕉橙 |
如果列的 rest 為 1,我想創建並改變列“frutis_name”。例如,蘋果和橙子得到 1,那么“frutis_name 將是蘋果空間香蕉。
使用purrr::map_chr()
:
df <- data.frame(apple = c(1,1), banana = c(0,0), orange = c(1,0))
df$fruit_name <- purrr::pmap_chr(df, ~ paste(names(df)[as.logical(c(...))], collapse = " "))
df
#> apple banana orange fruit_name
#> 1 1 0 1 apple orange
#> 2 1 0 0 apple
也許不是最簡單的解決方案,而是一個可行的解決方案,基於將列名重鑄為值的想法,這是由pivot_longer
完成的:
library(tidyverse)
df %>%
# create row ID:
mutate(row = row_number()) %>%
# cast longer so that fruit names become values:
pivot_longer(-row, names_to = "fruits") %>%
# for each combination of `row` and `value`...
group_by(row, value) %>%
# ... combine fruit names if `value == 1`:
mutate(fruits = ifelse(value == 1, str_c(fruits, collapse = " "), fruits)) %>%
# remove obsolete rows:
filter(value == 1 & !duplicated(fruits)) %>%
# deactivate grouping:
ungroup() %>%
# remove unnecessary columns:
select(-c(value, row)) %>%
# bind original `df` together with new `fruit` column:
bind_cols(df, .)
apple banana orange fruits
1 1 0 1 apple orange
2 1 0 0 apple
3 1 0 1 apple orange
4 1 1 1 apple banana orange
df$fruits_name <-
apply(df, 1, \(x) paste(names(df)[as.logical(x)], collapse = " "))
# apple banana orange fruits_name
# 1 1 0 1 apple orange
# 2 1 0 0 apple
# 3 1 0 1 apple orange
# 4 1 1 1 apple banana orange
相同的邏輯但更高效
library(data.table)
df$fruits_name <-
vapply(transpose(df), \(x) paste(names(df)[as.logical(x)], collapse = " "), character(1L))
可重現的數據
df <- data.frame(
apple = 1,
banana = c(0,0,0,1),
orange = c(1,0,1,1)
)
您可以使用apply
來做到這一點:
x <- data.frame(apple = c(1,0,1), banana = c(0,0,1), orange = c(1,0,0))
x$fruits_name <- apply(x, 1, function(y) paste(colnames(x)[y==1], collapse=" "), simplify = TRUE)
x
apple banana orange fruits_name
1 1 0 1 apple orange
2 0 0 0
3 1 1 0 apple banana
編輯:我用collapse
替換了sep
參數,現在它產生了一個向量,而不是一個列表
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.