I am working in R trying to generate several distinct vectors using a for loop.
First I created a small reproducible example data frame called df.
cluster.assignment <- c("1 Unknown", "1 Unknown", "2 Neuron","3
PBMC","4 Basket")
Value1 <- c("a","b","c","d","e")
Value2 <- c("191","234","178","929","123")
df <- data.frame(cluster.assignment,Value1,Value2)
df
cluster.assignment Value1 Value2
1 1 Unknown a 191
2 1 Unknown b 234
3 2 Neuron c 178
4 3 PBMC d 929
5 4 Basket e 123 .
Next I create a variable named clusters that includes keys to the datasets that I am interested in.
clusters <- c("1 ","4 ")
Here is my attempt to extract rownames of the data of interest in df using a for loop.
for (COI in clusters) {
name2 <- c(gsub(" ","", paste("Cluster", COI, sep = "_")))
assign(Cluster_1, name2, envir = parent.frame())
name2 <- grep(COI, df$cluster.assignment)
}
Desired output is two vectors called Cluster_1 and Cluster_4.
Cluster_1 would contain the values 1 and 2
Cluster_4 would contain the value 5
I can't seem to figure out how to assign the name of the COI variable to be the name of the output vector.