2

I create a dataframe called df and give column names to it. Then I create a new list called test_list. I loop through dataframe(df) and sort them in order.

Now, How do I print or extract only first 5 elements in the list(test_fun)?

df<- data.frame(45,67,78,89,45,65,54,67,87) 
colnames(df) <- c("A","B","C","D","E","F","G","H","I")

test_list <- list()

for(i in 1:nrow(df))
{
  test_list[[i]] <- colnames(sort(df[i,c(1:9)], decreasing = TRUE))
}

I tried,

test_list[[1]]

#gives output
#[1] "D" "I" "C" "B" "H" "F" "G" "A" "E"

test_list[c(1,2,3,4,5)]
#gives output
#[[1]]
#[1] "D" "I" "C" "B" "H" "F" "G" "A" "E"

#[[2]]
#NULL

#[[3]]
#NULL

#[[4]]
#NULL

#[[5]]
#NULL

But, I need

#output as
#D
#I
#C
#B
#H
Murlidhar Fichadia
  • 2,589
  • 6
  • 43
  • 93
  • 1
    Use `test_list[[1]]` to extract the vector and `test_list[[1]][1:5]` or `head(test_list[[1]], 5)` to extract the first 5 elements from the vector. [This post](http://stackoverflow.com/questions/36777567/is-there-a-logical-way-to-think-about-list-indexing/36815401) might be helpful in gaining a better understanding. – lmo Apr 06 '17 at 13:08
  • 1
    `head(unlist(test_list),5)` would do that trick too. – Joris Meys Apr 06 '17 at 13:09
  • Maybe it is intentional, are you aware the example dataframe in your post has only 1 row, and the loop only loops once? Hence NULLs in `test_list[c(1,2,3,4,5)]` – zx8754 Apr 06 '17 at 13:13

2 Answers2

5

Using head

head(test_list[[1]],5)
[1] "D" "I" "C" "B" "H"
989
  • 12,579
  • 5
  • 31
  • 53
Erdem Akkas
  • 2,062
  • 10
  • 15
0

The way you formatted your desired output, it looks like you want a list with 9 elements, not a list with one element that is a vector with 9 values. Can you say which one you prefer? If it's the former:

  for(i in 1:ncol(df))
  {
    test_list[[i]] <- colnames(sort(df[1,c(1:9)], decreasing = TRUE)[i])
  } 
head(test_list,5)
[[1]]
[1] "D"

[[2]]
[1] "I"

[[3]]
[1] "C"

[[4]]
[1] "B"

[[5]]
[1] "H"