[英]tidyverse concatenate characters across columns does not work with c_across
我有以下數據:
dat <- data.frame(sheet = c("a", "b", "c"),
condition1 = c("k", "l", "m"),
condition2 = c("x", "y", "z"))
我現在想使用連接這些列的 tidyverse 創建一個新列。 但是,我總是收到錯誤消息。
library(tidyverse)
new_dat %>%
rowwise() %>%
mutate(marker = str_c(c_across(c(sheet, starts_with("condition"))), sep = "/")) %>%
ungroup()
Error: Problem with `mutate()` input `marker`.
x Input `marker` can't be recycled to size 1.
i Input `marker` is `str_c(c_across(c(sheet, starts_with("condition"))), sep = "/")`.
i Input `marker` must be size 1, not 3.
i Did you mean: `marker = list(str_c(c_across(c(sheet, starts_with("condition"))), sep = "/"))` ?
i The error occurred in row 1.
任何建議/幫助?
預期輸出:
sheet condition1 condition2 marker
1 a k x a/k/x
2 b l y b/l/y
3 c m z c/m/z
注:我試過alyo的代碼不使用橫行一部分,使用across
而不是c_across
(和適應跨語法),但我發現了一個類似的錯誤。 更換str_c
通過paste0
也不起作用。
編輯:從輸入數據中刪除了 x 列,因為它沒有添加任何值。
使用collapse
,而不是sep
:
dat %>%
rowwise() %>%
mutate(marker = str_c(c_across(c(sheet, starts_with("condition"))),
collapse = "/")) %>%
ungroup()
# A tibble: 3 x 5
sheet condition1 condition2 x marker
<fct> <fct> <fct> <dbl> <chr>
1 a k x 1 a/k/x
2 b l y 2 b/l/y
3 c m z 3 c/m/z
你可以通過這個簡單的例子看到sep
和collapse
之間的區別(展示比解釋更容易):
str_c(letters[1:3], letters[4:6], sep = "_")
# "a_d" "b_e" "c_f"
str_c(letters[1:3], letters[4:6], collapse = "_")
# "ad_be_cf"
結合dplyr
和purrr
,您可以執行以下操作:
dat %>%
mutate(marker = pmap(across(c(sheet, starts_with("condition"))), paste, sep = "/"))
sheet condition1 condition2 x marker
1 a k x 1 a/k/x
2 b l y 2 b/l/y
3 c m z 3 c/m/z
您可以使用tidyr
的unite
:
tidyr::unite(dat, marker, sheet, starts_with('condition'),
sep = '/', remove = FALSE)
# marker sheet condition1 condition2 x
#1 a/k/x a k x 1
#2 b/l/y b l y 2
#3 c/m/z c m z 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.