简体   繁体   English

如何总结R中的字符

[英]how to summarize characters in r

I have a data frame: 我有一个数据框:

df <- data.frame(id = c("a","a","a","b","b","b"), survey = rep("1a",6), q1 = c(NA,NA,"y","n",NA,NA),q2 = c("y",NA,NA,NA,"y",NA), q3 = c(NA,"n",NA,NA,NA,"y"))

These are survey data which I need to collapse to one for each id and survey. 这些是调查数据,我需要针对每个ID和调查将其折叠为一个。 I can get close by: 我可以靠近:

df %>% group_by(id, survey) %>% summarize_all(toString)
Source: local data frame [2 x 5]
Groups: id [?]

      id survey        q1        q2        q3
    <fctr> <fctr>     <chr>     <chr>     <chr>
1      a     1a NA, NA, y y, NA, NA NA, n, NA
2      b     1a n, NA, NA NA, y, NA NA, NA, y

What I really need is: 我真正需要的是:

  id survey q1 q2 q3
1  a     1a  y  y  n
2  b     1a  n  y  y

The real data frame is fairly large (1.2 million records). 真实的数据帧相当大(120万条记录)。

Fundamentally different from suppress NAs in paste() . 抑制paste()中的NA根本不同。 Answer to my question not found there. 在这里找不到我的问题的答案。

A solution using base commands: 使用基本命令的解决方案:

for (i in 3:5) {df[,i] <- ifelse(df[,i] == "y", 1, 
                                 ifelse(df[,i] == "n", 0, df[,1]))}
df2 <- data.frame(aggregate(q1 ~ id + survey, df, FUN = sum), 
                  aggregate(q2 ~ id + survey, df, FUN = sum)[3], 
                  aggregate(q3 ~ id + survey, df, FUN = sum)[3])

Not sure how quick it'd be for a large df or compared to dplyr. 不确定大型df或与dplyr相比将有多快。 You may also want to replace the data.frame() call with merge() s if you expect missing replies for some id+survey combinations. 如果您希望某些ID +调查组合缺少答复,则可能还需要用merge()替换data.frame()调用。

最简单的解决方案是:

df %>% group_by(id, survey) %>% summarise_all(na.omit)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM