0

I'm recoding values to letters with the following line of code (which worked) :

df_mean$COMMUNITY_mean <- cut(df_mean$COMMUNITY_mean, breaks=c(0, 10, 25, 50, 75, 90, Inf), labels=c("a", "b", "c", "d", "e", "f"))

In order to apply it to multiple columns :

names <- colnames(df_mean) #extract columns names to a list
names <- names[-c(1:10)]; #remove 10 first columns not interested in


for(i in 1:length(names)) {                              
  df_mean <- cut(names[[i]], breaks=c(0, 10, 25, 50, 75, 90, Inf), labels=c("a", "b", "c", "d", "e", "f"))
  

}

But it fails to execute "Error in cut.default(names[[i]], breaks = c(0, 10, 25, 50, 75, 90, Inf), : 'x' must be numerical"
Any suggestions ?

  • 1
    It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Are you sure your columns are actually numeric values? The error message indicates at least column is not numeric so you can't use `cut()` on it – MrFlick Jun 02 '22 at 15:44
  • 2
    Try `df_mean[[names[i]]] <- cut(df_mean[[names[i]]], breaks=c(0, 10, 25, 50, 75, 90, Inf), labels=c("a", "b", "c", "d", "e", "f"))` i..e `names[i]` is just column names, you need to subset from the original data to get the column values – akrun Jun 02 '22 at 15:44
  • @MrFlick the columns of interest are numeric values. – Mathias Lauber Jun 02 '22 at 16:37
  • 1
    @akrun With the extra brackets, as you suggested, it works Thank you. – Mathias Lauber Jun 02 '22 at 16:37

1 Answers1

0

Try this in the first line

names <- colnames(df_mean[as.logical(lapply(df_mean , is.numeric))])
# remove this line ===> names <- colnames(df_mean)

to extract the numerical columns from your data

Mohamed Desouky
  • 4,340
  • 2
  • 4
  • 19