First I wrote the iris dataset, then I need to rename the setosa, virginica and versicolors to a,b and c. I then need to double-write these letters with a while loop. For example; I wrote b instead of Setosa, I should call it bb with while loop
Burak=iris
sehir= c("zonguldak","bilecik","samsun","sinop","letter")
for ( i in 1:ncol(Burak)) {
colnames(Burak)[i] = sehir[i]
}
head(Burak)
levels(iris$Species) <- c(levels(iris$Species), "a")
iris$Species[iris$Species == 'virginica'] <- 'a'
levels(iris$Species) <- c(levels(iris$Species), "b")
iris$Species[iris$Species == 'setosa'] <- 'b'
levels(iris$Species) <- c(levels(iris$Species), "c")
iris$Species[iris$Species == 'versicolor'] <- 'c'
running_index <- 5
while(is.character(iris[ , running_index])) {
iris[ , running_index] <- iris[ , running_index] a
running_index <- running_index 5
}
CodePudding user response:
Here is a way.
- Find out which columns are factors with a
sapply
loop: - Coerce those factors to character;
- Find out which columns are of class character;
- Finally, do the required transformation in a
lapply
loop.
data(iris, package = "datasets")
Burak <- iris
sehir <- c("zonguldak","bilecik","samsun","sinop","letter")
names(Burak) <- sehir
i_fac <- sapply(Burak, is.factor)
Burak[i_fac] <- lapply(Burak[i_fac], as.character)
i_chr <- sapply(Burak, is.character)
Burak[i_chr] <- lapply(Burak[i_chr], \(x) {
x <- letters[match(x, unique(x))]
paste0(x, x)
})
head(Burak)
#> zonguldak bilecik samsun sinop letter
#> 1 5.1 3.5 1.4 0.2 aa
#> 2 4.9 3.0 1.4 0.2 aa
#> 3 4.7 3.2 1.3 0.2 aa
#> 4 4.6 3.1 1.5 0.2 aa
#> 5 5.0 3.6 1.4 0.2 aa
#> 6 5.4 3.9 1.7 0.4 aa
str(Burak)
#> 'data.frame': 150 obs. of 5 variables:
#> $ zonguldak: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
#> $ bilecik : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
#> $ samsun : num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
#> $ sinop : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
#> $ letter : chr "aa" "aa" "aa" "aa" ...
Created on 2022-12-16 with reprex v2.0.2
If you need the original factors to still be factors, run
Burak[i_fac] <- lapply(Burak[i_fac], as.factor)
The code above can be rewritten in just one lapply
loop. The results are identical.
Burak[] <- lapply(Burak, \(x) {
y <- if(is.factor(x)) as.character(x) else x
if(is.character(y)) {
u <- unique(y)
y <- letters[match(y, u)]
y <- paste0(y, y)
}
if(is.factor(x)) y <- factor(y)
y
})
Created on 2022-12-16 with reprex v2.0.2