I have a dataframe with a character column and 4 numeric columns.
What I want to do is to apply filtering according to each column and create new data frames from each of them.
Here is an example data frame:
df <- data.frame(my_names=sample(LETTERS,4,replace=F),
column2=sample(1.3:100.3,4,replace=T),
column3=sample(1.3:100.3,4,replace=T),
column4=sample(1.3:100.3,4,replace=T),
column5=sample(1.3:100.3,4,replace=T))
> df
my_names column2 column3 column4 column5
1 A 8.3 1.3 19.3 91.3
2 E 18.3 42.3 8.3 76.3
3 O 6.3 46.3 26.3 91.3
4
What I want to get, for one column (here column2) is this:
top <- 2
top_column2 <- df %>% arrange(desc(column2)) %>%
select(my_names, column2) %>%
top_n(top, column2) %>%
mutate(column2=round(column2))
> top_column2
my_names column2
1 O 76
2 E 75
This works perfectly fine.
Now I would like to iterate
-the naming of the data frames and
-the creation of the data frames
for columns 2:5
I first tried doing:
> for(i in 2:ncol(df)) {
+ paste("top", colnames(df)[i], sep="_") <-
+ df %>% arrange(desc(i)) %>% select(my_names, i) %>% top_n(top, i) %>% mutate(i=round(i))
+ }
Error in paste("top", colnames(df)[i], sep = "_") <- df %>% arrange(desc(i)) %>% :
target of assignment expands to non-language object
After googling, tried assign(paste(), functions):
for(i in 2:ncol(df)) {
assign(paste("top", colnames(df)[i], sep="_"),
df %>% arrange(desc(i)) %>% select(my_names, i) %>% top_n(top, i) %>% mutate(i=round(i)))
}
top_column4
> top_column4
my_names column4 i
1 A 19.3 4
2 E 8.3 4
3 O 26.3 4
4 M 59.3 4
This creates 4 data frames with the right names, but the functions are not applied and a new column is created.
More googling, trying now with an empty list to then change its elements:
test_list <- list()
for(i in 2:ncol(df)) {
test_list[[paste("top", colnames(df)[i], sep="_")]] <-
df %>% arrange(desc(i)) %>% select(my_names, i) %>% top_n(top, i) %>% mutate(i=round(i))
}
> top_column4
my_names column4 i
1 A 19.3 4
2 E 8.3 4
3 O 26.3 4
4 M 59.3 4
But here's the same problem as with assign(), the data frames are created with the right names, but not the right content.
Could someone please help to solve this issue?