I have a large dataframe with utterances of variable sizes:
df <- structure(list(size = c(2, 2, 3, 3, 4, 4, 3, 3),
w1 = c("come", "why", "er", "well", "she", "well", "er", "well"),
w2 = c("on","that", "i", "not", "'s", "thanks", "super", "she"),
w3 = c(NA, NA, "can", "today", "going", "they", "cool", "can"),
w4 = c(NA,NA, NA, NA, "on", "can", NA, NA)),
row.names = c(NA, -8L), class = "data.frame")
I'd like to compare the utterance-initial words in w1 with all the utterance-final words in the other w columns with frequency lists with counts and proportions. I can compute a frequency list of the utterance-initial words:
library(dplyr)
df %>%
group_by(w1) %>%
summarise(n = n()) %>%
mutate(prop = n / sum(n)) %>%
arrange(desc(prop))
# A tibble: 5 x 3
w1 n prop
<chr> <int> <dbl>
1 well 3 0.375
2 er 2 0.25
3 come 1 0.125
4 she 1 0.125
5 why 1 0.125
But how to compute the list of the utterance-final words when these are in different w columns?
Expected:
# A tibble: 5 x 3
w_last n prop
<chr> <int> <dbl>
1 can 3 0.375
2 on 2 0.25
3 cool 1 0.125
4 that 1 0.125
5 today 1 0.125
Here's at long last another solution:
df %>%
mutate(w_last = c(apply(., 1, function(x) tail(na.omit(x), 1)))) %>%
group_by(w_last) %>%
summarise(n = n()) %>%
mutate(prop = n / sum(n)) %>%
arrange(desc(prop))