I am trying to assign the factor output of a for loop to a variable named after the index i.
My data 'dat' has five variables:
str(dat)
'data.frame': 1771 obs. of 5 variables:
$ Replicate: chr "at20201119" "at20201119" "at20201119" "at20201119" ...
$ Treatment: chr "Buffer" "Buffer" "Buffer" "Buffer" ...
$ Host : chr "w4k1-1" "w4k1-1" "w4k1-1" "w4k1-1" ...
$ count : int 113 181 72 32 168 111 77 56 17 42 ...
$ count_mm2: num 32.08 51.38 20.44 9.08 47.69 ...
I want to extract all values of Replicate
that are returned when I print all rows where Host == (a value of interest, e.g. w4k1-1)
First I used split()
to split the levels of dat$Host
into distinct dfs with dat_list <- split(dat, as.factor(dat$Host))
str(dat_list)
List of 12
$ Col-0 :'data.frame': 352 obs. of 5 variables:
..$ Replicate: chr [1:352] "at20201119" "at20201119" "at20201119" "at20201119" ...
..$ Treatment: chr [1:352] "Buffer" "Buffer" "Buffer" "DC3000" ...
..$ Host : chr [1:352] "Col-0" "Col-0" "Col-0" "Col-0" ...
..$ count : int [1:352] 41 136 58 257 47 88 324 182 174 176 ...
..$ count_mm2: num [1:352] 11.6 38.6 16.5 73 13.3 ...
# this is followed by 11 more df of the same structure
Then, and this is where I'm stuck. I try to use a for loop to get factored values of dat_list.
for (i in names(dat_list)){
i <- levels(factor(dat_list$`i`$Replicate))
}
This returns empty character vectors for each returned value of names(dat_list)
(so, 12 empty character vectors) and also a variable i
with the value of the 12th element of the names(dat_list)
output. But if I were to input
levels(factor(dat_list$`Col-0`$Replicate))
it returns:
[5] "at20201125" "at20201203" "at20201204" "at20201210"
[9] "at20201217" "at20201224" "at20201231" "W.006"
[13] "W.007" "W.008" "W.010" "W.011"
[17] "W.014"
which is the desired output.
So, why won't my loop output what I want it to?
This is my first time posting a question- I've done my best to provide all the information I think is necessary- thank you very much for any help.