R-制表字符向量-自定义输出
我想将一些小字符向量的值制成表格,并将表格结果附加到字符串中。对于下面的可复制示例,我希望的输出如下所示:R-制表字符向量-自定义输出,r,R,我想将一些小字符向量的值制成表格,并将表格结果附加到字符串中。对于下面的可复制示例,我希望的输出如下所示: states responsible 1 KS Joe(2);Suzie(3) 2 MO Bob(4) 3 CO Suzie(1);Bob(2);Ralph(3) 4 NE Joe(1) 5 MT
states responsible
1 KS Joe(2);Suzie(3)
2 MO Bob(4)
3 CO Suzie(1);Bob(2);Ralph(3)
4 NE Joe(1)
5 MT Suzie(3);Ralph(1)
以下是示例数据:
states <- c("KS", "MO", "CO", "NE", "MT")
responsible <- list(c("Joe", "Joe", "Suzie", "Suzie", "Suzie"), c("Bob", "Bob", "Bob", "Bob"), c("Suzie", "Bob", "Ralph", "Ralph", "Bob", "Ralph"), "Joe", c("Suzie", "Ralph", "Suzie", "Suzie"))
df <- as.data.frame(cbind(states, responsible))
#Tabulating using table()
resp.tab <- lapply(responsible, table)
#Is there a way I can do tabulation without converting to factors?
# OR
#Is there a way to access the factor label and value, then paste them together?
状态我们可以使用数据表
。通过复制长度为'responsible'的'states'和长度为'responsible'的'states'来创建一个data.table
library(data.table)
dt1 <- data.table(states= rep(states, lengths(responsible)),
responsible=unlist(responsible))
或者类似的选项与dplyr/tidyr
library(dplyr)
library(tidyr)
tbl_df(dt1) %>%
group_by(states, responsible) %>%
tally() %>%
unite(responsible, responsible, n, sep="(") %>%
group_by(states) %>%
summarise(responsible = paste(paste0(responsible, ")"), collapse=";"))
表格
也适用于字符
向量。
library(dplyr)
library(tidyr)
tbl_df(dt1) %>%
group_by(states, responsible) %>%
tally() %>%
unite(responsible, responsible, n, sep="(") %>%
group_by(states) %>%
summarise(responsible = paste(paste0(responsible, ")"), collapse=";"))