Ich bin relativ neu bei R, also entschuldige mich, wenn das so weit daneben liegt. Aber ich habe einen Datensatz, der ungefähr so aussieht:
#simplified input - actual data has ~20K observations,
#V1 is a categorical variable with 2 options, V3 is a categorical variable with 23 options
df <- tribble(
~V1, ~V2, ~V3,
"A", "a", "Z",
"A", "a", "Y",
"A", "b", "X",
"A", "b", "Z",
"B", "c", "Z",
"B", "a", "Z",
"B", "a", "Y",
"A", "d", "X",
"A", "e", "X",
"A", "f", "X",
"A", "g", "X",
"B", "g", "X",
"B", "h", "X",
"A", "i", "X",
)
Und ich versuche, die unterschiedlichen Werte von V2 basierend auf einer Kombination von V1 und V3 zu zählen. In diesen Beispieldaten ist "a" in A und B zu finden und kann als Z oder Y klassifiziert werden. Die Ausgabe, die ich mir vorstelle, würde also etwa so aussehen, wobei die Zahlen die eindeutige Anzahl von V2 sind:
Die gewünschte Ausgabe:
df <- tribble(
~V1, ~Z, ~Y, ~X,
"A_only", 1, 0, 5,
"B_only", 1, 0, 1,
"Both_A_and_B", 1, 1, 1
)
Ich bin ehrlich gesagt völlig ratlos, wie das geht, also wäre ich für alle Gedanken dankbar.
Aktualisiert
Das Problem gelöst!
library(dplyr)
library(tidyr)
df %>%
group_by(V1, V2, V3) %>%
add_count() %>%
pivot_wider(names_from = V3, values_from = n) %>%
group_by(V2) %>%
mutate(V1 = ifelse(length(V2) > 1, "Both_A_and_B",
ifelse(length(V2) == 1 & V1 == "A", "A_only",
"B_only"))) %>%
distinct() %>%
group_by(V1) %>%
summarise(across(Z:X, ~ sum(.x, na.rm = TRUE)))
# A tibble: 3 x 4
V1 Z Y X
<chr> <int> <int> <int>
1 A_only 1 0 5
2 B_only 1 0 1
3 Both_A_and_B 1 1 1
Dieser Artikel stammt aus dem Internet. Bitte geben Sie beim Nachdruck die Quelle an.
Bei Verstößen wenden Sie sich bitte [email protected] Löschen.
Lass mich ein paar Worte sagen