Eday Gonzalez
Eday Gonzalez

Reputation: 310

Group and summarise character in R?

I this in R

> con_promedio_por_curso_transpuesta
                A          B          C           D
Description   "Abc"     "Bcd"      "Cde"      "Def"
mean(X7)  "5.000000" "4.105263" "4.733333"  "4.680000"
mean(X8)  "5.000000" "3.736842" "4.400000"  "4.760000"     
mean(X9)  "5.000000" "3.950000" "4.600000"  "4.840000"
mean(X10) "5.000000" "4.210526" "4.333333"  "4.560000"

I want to delete the first row

"Abc"     "Bcd"      "Cde"      "Def"

I run the next instruction:

without_first_row <- con_promedio_por_curso_transpuesta[-c(1),])

Until now, everything is OK, but. If I want to group and summarise the without_first_row I get an error.

Error in UseMethod("group_by_") : no applicable method for 'group_by_' applied to an object of class "c('matrix', 'character')"

I run the type of data,

> typeof(con_promedio_por_curso_transpuesta)
[1] "character"

How I cast "character" to any type of data for grouping ?

Thanks.

Upvotes: 0

Views: 546

Answers (1)

parkerchad81
parkerchad81

Reputation: 558

You have an error in your syntax near where you create without_first_row, follow along below:

con_promedio_por_curso_transpuesta <-
  data.frame(
    row.names = c('Description','mean(X7)','mean(X8)','mean(X9)','mean(X10)'),
    'A' = c("Abc","5.000000","5.000000","5.000000","5.000000"),
    'B' = c("Bcd","4.105263","3.736842","3.950000","4.210526"),
    'C' = c("Cde","4.733333","4.400000","4.600000","4.333333"),
    'D' = c("Def","4.680000","4.760000","4.840000","4.560000"),
    'ID' = c(NA, 1, 1, 2, 2) # added for this example
  )

## without_first_row <- con_promedio_por_curso_transpuesta[-c(1), ]) <- this is your error, you added a ')' unnecessarily

without_first_row <- con_promedio_por_curso_transpuesta[-c(1), ] # with fixed syntax
> class(without_first_row)
[1] "data.frame"


# just to show you can group_by and summarise with data
without_first_row %>% 
  mutate_at(.vars = vars(c(A,B,C,D)), funs(as.numeric)) %>% 
  group_by(ID) %>% 
  summarise_all(mean)

Upvotes: 1

Related Questions