[R] Simple loop problem
William Dunlap
wdunlap at tibco.com
Mon Oct 31 20:46:31 CET 2016
Did you mean 'tolower' instead of 'to lower' in your example?
Or is there a similarly named function that converts the levels
of a factor to lower case instead of converting the factor to
a character vector and then lower-casing that?
> d %>% dplyr::mutate_if(is.factor, tolower)
Num F1 F2
1 1 one a
2 2 two b
3 3 three a
> str(.Last.value)
'data.frame': 3 obs. of 3 variables:
$ Num: int 1 2 3
$ F1 : chr "one" "two" "three"
$ F2 : chr "a" "b" "a"
Bill Dunlap
TIBCO Software
wdunlap tibco.com
On Mon, Oct 31, 2016 at 12:39 PM, Yahya Laraki <larakiyahya at gmail.com>
wrote:
> Thank you for your help! I found this solution much simpler:
> d <- data.frame(Num=1:3, F1=c("One","Two","Three"), F2=c("A","B","a »))
> d %>% mutate_if(is.factor, to lower)
>
> Thank you again for taking time to respond!!
>
> Yahya
>
> Le 31 oct. 2016 à 15:28, William Dunlap <wdunlap at tibco.com> a écrit :
>
> 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/posti
>> ng-guide.html <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