Подсчет отдельных строк в столбцах - PullRequest
0 голосов
/ 19 сентября 2019

Я хочу посчитать количество «Согласен» и «Не согласен» в каждом столбце.Все, что я сделал до сих пор, это некоторая перекодировка данных, но как мне получить счетчики для каждого столбца.Я пробовал summarise_all, но это не сработало.Я пытаюсь работать в dplyr

new<-subjects1%>%
  filter(Qx1_mod1=='Health, Public Services and Care')%>%
  mutate_all(funs(str_replace(., "Strongly agree", "Agree")))%>%
  mutate_all(funs(str_replace(., "Strongly disagree", "Disagree")))%>%
  mutate_all(funs(str_replace(., "Neither agree nor disagree", "Neither")))

Ответы [ 3 ]

1 голос
/ 19 сентября 2019

Базовый раствор R:

df <- data.frame(
  col1 = c("", "somewhat agree", "agree"),
  col2 = c("", "I agree", "agree"),
  col3 = c("agree", "agree", "agree"),
  col4 = c("disagree", "agree, Agree", "agree, agree"), stringsAsFactors = FALSE
)

pattern <- "(^a| a)gree"
res <- colSums(apply(df, 2, function(x, s = pattern) grepl(s, x, ignore.case = TRUE)))

> res
# col1 col2 col3 col4 
#   2    2    3    2 
0 голосов
/ 19 сентября 2019

Если вы хотите создать простую таблицу частот, вы всегда можете использовать table, например:

col_1 <- c("Agree","Agree","Disagree","Neither","Disagree", "Agree")
col_2 <- c("Neither","Neither","Disagree","Neither","Disagree", "Agree")

data.frame(col_1,col_2) %>%
  gather(columns,values) %>%
  table()

# output 
columns Agree Disagree Neither
  col_1     3        2       1
  col_2     1        2       3
0 голосов
/ 19 сентября 2019

Простая настройка будет выглядеть примерно так:

library(dplyr)
library(stringr)
subjects1 <- tibble(
  col1 = c("", "", "agree"),
  col2 = c("", "agree", "agree"),
  col3 = c("agree", "agree", "agree"),
  col4 = c("agree", "agree, agree", "agree, agree"),
  col5 = c("disagree", "agree, Agree", "Neither")
)

subjects1 %>% 
  mutate_all(function(x) str_count(x,  regex(pattern = "\\bagree\\b", ignore_case = TRUE))) %>%
  colSums()
#> col1 col2 col3 col4 col5 
#>    1    2    3    5    2

Создано в 2019-09-19 с помощью пакета Представить (v0.3.0)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...