[R] Simple loop problem

William Dunlap wdunlap at tibco.com
Mon Oct 31 20:28:51 CET 2016


Use tolower on the levels of the factor columns.  E.g.,

> d <- data.frame(Num=1:3, F1=c("One","Two","Three"), F2=c("A","B","a"))
> str(d)
'data.frame':   3 obs. of  3 variables:
 $ Num: int  1 2 3
 $ F1 : Factor w/ 3 levels "One","Three",..: 1 3 2
 $ F2 : Factor w/ 3 levels "a","A","B": 2 3 1
> for(n in names(d))
+    if (is.factor(d[[n]])) levels(d[[n]]) <- tolower(levels(d[[n]]))
> str(d)
'data.frame':   3 obs. of  3 variables:
 $ Num: int  1 2 3
 $ F1 : Factor w/ 3 levels "one","three",..: 1 3 2
 $ F2 : Factor w/ 2 levels "a","b": 1 2 1

Using data.frame(tolower(as.matrix(d))) may change your column names
and the data in your columns - don't do it.


Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Mon, Oct 31, 2016 at 7:44 AM, Yahya Laraki <larakiyahya at gmail.com> wrote:

> Hi everybody,
>
> I’m new to R and i’m trying to learn fundamentals. I’m facing a small
> problem for which i can’t find a solution online.
>
> What i want to do: write a function to lower case for all the columns in
> my data.frame if they respect a condition (class = factor)
>
> This code works, but for all my columns : change_lower = function(x)
> {data.frame(tolower(as.matrix(x)))}
>
> I need more something like this, but it doesn’t work: function (x) { for
> (i in 1:length(x)) {
>   if (class(i)=="factor") {
>     data.frame(tolower(as.matrix(x)))
>   }
> }}
>
> Thank you
>
> Yahya
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.

	[[alternative HTML version deleted]]



More information about the R-help mailing list