Reputation: 2049
A data.frame "df"
st1 st2 st3 st4 st5
1 0 0 0 0 0
2 0 0 0 0 0
3 0 0 0 0 0
4 0 0 0 0 0
5 0 0 0 0 0
6 0 0 0 0 0
is to be updated based on a vector. The vector is returned from some function call and every time, it may contain varying number of columns but the vector columns are always present in data.frame "df".
for (i in 1:10)
{
x<-funcall()
print(x)
# time.chosen
#st3 2
#st5 4
// Update data.frame "df"
}
Is there any simple way to do this kind of update in R?
UPDATED: Lets suppose, for 1st iteration of for loop, x is
time.chosen
st3 2
st5 4
then the data.frame df should look like following
st1 st2 st3 st4 st5
1 0 0 2 0 4
2 0 0 0 0 0
3 0 0 0 0 0
4 0 0 0 0 0
5 0 0 0 0 0
6 0 0 0 0 0
Each iteration of loop correspond to a row in data.frame df.
Upvotes: 1
Views: 2957
Reputation: 121568
Somehing like this should work:
df[iter,rownames(vector)] <- vector$time.chosen
Here I assume that vector is a data.frame like this :
Here an example :
vector = data.frame(time.chosen= c(1,2))
rownames(vector) <- paste('t',c(2,3),sep='')
time.chosen
t2 1
t3 2
df <- as.data.frame(diag(5)*0)
colnames(df) <- paste('t',c(1:5),sep='')
iter <- 1
df[iter,rownames(vector)] <- vector$time.chosen
t1 t2 t3 t4 t5
1 0 1 2 0 0
2 0 0 0 0 0
3 0 0 0 0 0
4 0 0 0 0 0
5 0 0 0 0 0
iter <-4
df[iter,rownames(vector)] <- vector$time.chosen
t1 t2 t3 t4 t5
1 0 1 2 0 0
2 0 0 0 0 0
3 0 0 0 0 0
4 0 1 2 0 0
5 0 0 0 0 0
Upvotes: 1