I need to use a for loop that can add column 1 to column 3,5,7,9,11,13,15,17 and sort column 2,4,6,8,10,12.14,16,18
I tried to use for but am having difficulties in applying it
first_column<- c("^","G","A","T","T","A","C","A")
second_column<- sort(first_column)
third_column<-paste(first_column,second_column)
fourth_column<-sort(third_column)
fifth_column<-paste(first_column,fourth_column)
sixth_column<-sort(fifth_column)
seventh_column<-paste(first_column,sixth_column)
eight_column<-sort(seventh_column)
ninth_coulmn<-paste(first_column,eight_column)
tenth_coulmn<-sort(ninth_coulmn)
elventh_coulmn<-paste(first_column,tenth_coulmn)
twelveth_coulmn<-sort(elventh_coulmn)
df<-data.frame(first_column,second_column,third_column,fourth_column,fifth_column,sixth_column,seventh_column,eight_column,ninth_coulmn,tenth_coulmn,elventh_coulmn,twelveth_coulmn)
df
CodePudding user response:
We may create a condition in the for
loop
df <- data.frame(first_column = c("^","G","A","T","T","A","C","A"))
df$second_column <- sort(df$first_column)
library(english)
or(i in 3:12) {
if(i %%2 != 0) {
df[[i]] <- paste(df[[1]], df[[i-1]])
} else {
df[[i]] <- sort(df[[i-1]])
}
names(df)[i] <- paste0(ordinal(i), "_column")
}
-output
> df
first_column second_column third_column fourth_column fifth_column sixth_column seventh_column eighth_column ninth_column tenth_column eleventh_column
1 ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
2 G A G A A A G A A A A G G A A G A A G A G A A G A A A G A A G A A G A A
3 A A A A A G A A G A G A A A G A A G A A A A G A A A G A A G A A G A A G
4 T A T A A T T A T A T C T A T C A T C T T A T C T A T C T A T A T C T A
5 T C T C C T T C T C T A T C T A C T A T T C T A T C T A T C T C T A T C
6 A G A G G A A G A G A A A G A A G A A G A G A A G G A A G A A G A A G A
7 C T C T T A C T A T A T C T A T T A T C C T A T C T A T C T C T A T C T
8 A T A T T C A T C T C T A T C T T C T A A T C T A T C T A T A T C T A T
twelfth_column
1 ^ ^ ^ ^ ^ ^
2 A A G A A G
3 A G A A G A
4 A T C T A T
5 C T A T C T
6 G A A G A A
7 T A T C T A
8 T C T A T C
CodePudding user response:
list_col <- vector("list", length = 18)
list_col[[1]] <- first_column <- c("^","G","A","T","T","A","C","A")
for (i in 2:18) {
if (i %% 2 == 0) {
list_col[[i]] <- sort(list_col[[i - 1]])
} else {
list_col[[i]] <- paste(first_column, list_col[[i - 1]])
}
}
list_col |>
as.data.frame() %>%
setNames(paste0("col", 1:18))