Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R-制表字符向量-自定义输出_R - Fatal编程技术网

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=";"))