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
Well the answer lies in the error warning.
nchar
requires a character vector, whichsapply
will not provide here (When debugged, the output ofsapply
is "factor" not "character"). You have to useapply
instead:Note: It is not good practice to use built-in function names for naming custom objects. So I changed
df
todf1
. And also the output requires transpose byt
to confirm with your required output.