Consider this toy data frame:
df <- read.table(text = "target birds wolfs
0 21 7
0 8 4
1 2 5
1 2 4
0 8 3
1 1 12
1 7 10
1 1 9 ",header = TRUE)
I would like to run a loop function that will calculate the mean per each variable's 2:5 rows and save all results as a CSV.
I wrote this line of code:
for(i in names(df)) {print(mean(df[2:5,i]))}
and got the following results:
[1] 0.5
[1] 5
[1] 4
But when I tried to export it to csv using the code below I got in the file only the last result: [1] 4. code:
for(i in names(df)) { j<-(mean(df[2:5,i]))
write.csv(j,"j.csv") }
How can I get in the same csv file a list of all the results?