R script - nchar(x) function is not working in sapply

842 views Asked by At

when I try to apply an sapply funcion to a data.frame, it does not work and I get this error:

"Error in nchar(x) : 'nchar()' requires a character vector"

the sapply funcion is:

as.data.frame(sapply(df,function(x) nchar(x))) 

my test.data frame is:

df<-data.frame(valor1=c("R$ 27.144,22"," 30.035,07 "," 30.761,40 "),valor2=c("17.935,85","13.741,63","19.090,80"),valor3=c("0,00","0,00","1"))

I dont understand why I get that error because I've propperly formated my data frame as follows

df <- as.data.frame(sapply(df,as.character)) 

what I would want as a result would be a new data.frame were each element is the number of characters of each element in the older data.frame. In my test data.frame example, that would be:

valor1           valor2       valor3
[1]12              9               4
[2]11              9               4
[3]11              9               1
1

There are 1 answers

0
S.C On BEST ANSWER

Well the answer lies in the error warning. nchar requires a character vector, which sapply will not provide here (When debugged, the output of sapply is "factor" not "character"). You have to use apply instead:

ncharsap <- function() {
    df1 <-data.frame(valor1=c("R$ 27.144,22"," 30.035,07 "," 30.761,40 "),valor2=c("17.935,85","13.741,63","19.090,80"),valor3=c("0,00","0,00","1"))
    df1 <- as.data.frame(sapply(df1,as.character)) 
    df2 <- t(as.data.frame(apply(df1,1, function(x) nchar(x))))
    return(df2)
}

Note: It is not good practice to use built-in function names for naming custom objects. So I changed df to df1. And also the output requires transpose by t to confirm with your required output.