Re: [R] Qualitative Data??(String command)

From: John Fox <jfox_at_mcmaster.ca>
Date: Fri 27 Oct 2006 - 21:18:32 GMT


Dear Davia,

> -----Original Message-----
> From: r-help-bounces@stat.math.ethz.ch
> [mailto:r-help-bounces@stat.math.ethz.ch] On Behalf Of Davia Cox
> Sent: Friday, October 27, 2006 3:37 PM
> To: r-help@stat.math.ethz.ch
> Subject: [R] Qualitative Data??(String command)
>
> I am using the read.table function to load an Excel data set into R.
> It has a few variables with very long qualitative (free
> response typically in sentences) response that I would like
> to keep, but would like to limit the "length" of the response
> that R shows. Is there some sort of string or column width
> command I can include in the read.table function to limit the
> length of words used in the variables that have long
> responses?? I do know which variable names are the ones with
> the qualitative responses. Will the Rcmdr program do this for
> me?

No. When you read an Excel file (or an ascii file) into R using the Rcmdr, character data will be converted into factors.

> I know STATA has this function but I don't have it on my
> computer to use.
>

If I understand you correctly, it's not hard to do what you want. The following function takes a data frame and desired character length as arguments and truncates both character variables and the levels of factors. Note that you have to be a little careful with factors in that you could truncate different levels to the same string, inadvertently combining them.

truncateValues <- function(Data, len=10){

    for (i in 1:ncol(Data)){

        var <- Data[[i]]
        if (is.factor(var)) {
            levels(var) <- sapply(levels(var), 
                function(x) substr(x, 1, min(nchar(x), len)))
            Data[[i]] <- var
            }
        else if (is.character(var)) {
            Data[[i]] <- sapply(var, function(x) substr(x, 1, min(nchar(x),
len)))
            }
        }

    Data
    }

I hope this helps,
 John

> Davia
>
>
> --
> Davia S. Cox
> "Image creates desire. You will what you imagine."
> ~J.G. Gallimore~
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Sat Oct 28 07:29:36 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 27 Oct 2006 - 22:30:14 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.