Jak indeksować element obiektu list w R
Wykonuję następujące czynności, aby zaimportować niektóre tabele txt i zachować je jako listę:
# set working directory - the folder where all selection tables are stored
hypo_selections<-list.files() # change object name according to each species
hypo_list<-lapply(hypo_selections,read.table,sep="\t",header=T) # change object name according to each species
Chcę uzyskać dostęp do jednego konkretnego elementu, powiedzmy hypo_list[1]. Ponieważ każdy element reprezentuje tabelę, w jaki sposób powinienem uzyskać dostęp do poszczególnych komórek (wierszy i kolumn)?
Chciałbym zrobić coś takiego:
a<-hypo_list[1]
a[1,2]
Ale dostaję następujący komunikat o błędzie:
Error in a[1, 2] : incorrect number of dimensions
Czy jest na to jakiś sprytny sposób?
Z góry dzięki! 1 answers
Indeksowanie listy odbywa się za pomocą podwójnego nawiasu, tzn. hypo_list[[1]]
(np. spójrz tutaj: http://www.r-tutor.com/r-introduction/list ). BTW: read.table
nie zwraca tabeli, lecz ramki danych(patrz sekcja wartość w ?read.table
). Więc będziesz miał listę ramek danych, a nie listę obiektów tabeli. Główny mechanizm jest jednak identyczny dla tabel i RAM danych.
Uwaga : W R indeks dla pierwszego wpisu to 1
(nie 0
jak w innych języki).
Dataframes
l <- list(anscombe, iris) # put dfs in list
l[[1]] # returns anscombe dataframe
anscombe[1:2, 2] # access first two rows and second column of dataset
[1] 10 8
l[[1]][1:2, 2] # the same but selecting the dataframe from the list first
[1] 10 8
Obiekty tabeli
tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2) # put tables in a list
tbl1[1:2] # access first two elements of table 1
Teraz z listą
l[[1]] # access first table from the list
1 2 3 4 5
9 11 12 9 9
l[[1]][1:2] # access first two elements in first table
1 2
9 11
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-25 09:39:04