I would like to change the name of attributes within a column that are sampled from a loop. In the first for
loop, I am taking a sample from my entire dataset and in the 2nd for
loop, placing this sample in an empty dataframe that I created. Everything functions as I need it except the renaming code. My renaming solution almost works, but I need the rename in sequential order from 1 to 9.
With dummy data:
AllFruit <- read.table("AllFruitData.txt")
for (i in 1:1000) {
Fruit.sample <- sample(AllFruit$Weight, size = 9, replace = TRUE) #create a sample based on weight of fruit
WeightSample <- NULL #create an empty dataframe
for (k in 1:length(Fruit.sample)) {
WeightSample = rbind(WeightSample, AllFruit[which(AllFruit$Weight == Fruit.sample[k]),])
}
}
What this yields:
WeightSample
Type Color Weight
Apple Red 5
Banana Yellow 5
Apple Red 5
Apple Red 9
Banana Yellow 9
Orange Orange 7
Pear Green 3
Banana Yellow 8
Pear Green 6
Pear Green 2
Banana Yellow 1
Pear Green 1
Pear Green 4
What I need:
Type Color Weight
Apple Red 1
Banana Yellow 1
Apple Red 1
Apple Red 2
Banana Yellow 2
Orange Orange 3
Pear Green 4
Banana Yellow 5
Pear Green 6
Pear Green 7
Banana Yellow 8
Pear Green 8
Pear Green 9
To rename the weights in my Weight column, I have deduced that I need to change the right side of the arrow because when I add this into the 2nd loop after the rbind
line:
WeightSample[WeightSample$Weight == Fruit.sample[k], "Weight"] <- 13
I get:
Type Color Weight
Apple Red 13
Banana Yellow 13
Apple Red 13
Apple Red 13
Banana Yellow 13
Orange Orange 13
Pear Green 13
Banana Yellow 13
Pear Green 13
Pear Green 13
Banana Yellow 13
Pear Green 13
Pear Green 13
I have tried a few options such as seq(1:9)
but get a replacement error. Since I am sampling 1000 times, I need a solution that will account for the weight of each new sample. Thank you!